码迷,mamicode.com
首页 > 其他好文 > 详细

mongoose CastError: Cast to ObjectId failed for value

时间:2015-06-17 16:35:08      阅读:204      评论:0      收藏:0      [点我收藏+]

标签:

restfull路由如下:

router.get(‘/:id‘, controller.show);

mongoes代码如下:
exports.show = function(req, res) {
  Notice.findById(req.params.id, function (err, notice) {
    if(err) {
      res.json({no:0,msg:‘获取失败:‘+err});
    }else{
      var result = {no:1};
      result.obj=notice;
      res.json(result);
    }
  });
};

客户端访问:

http://192.168.0.165:9000/api/notices/11

打印结果如下;

{
"no": 0,
"msg": "获取失败:CastError: Cast to ObjectId failed for value \"11\" at path \"_id\""
}

具体原因参考:

http://stackoverflow.com/questions/14940660/whats-mongoose-error-cast-to-objectid-failed-for-value-xxx-at-path-id

Mongoose‘s findById method casts the id parameter to the type of the model‘s _id field so that it can properly query for the matching doc. This is an ObjectId but "11" is not a valid ObjectId so the cast fails.

 

如果客户端传递的是mongo ObjectId就不会报以上错误.例如以下访问方式:

http://192.168.0.165:9000/api/notices/41224d776a326fb40f000001 就不会报错.

{
"no": 1,
"obj": null
}

 

在正常情况下,客户端传递的id参数是从后台获取的ObjectId,但是为了严谨性现在做以下处理:

exports.show = function(req, res) {
  var id = req.params.id;

  if (id.match(/^[0-9a-fA-F]{24}$/)) {
    Notice.findById(id, function (err, notice) {
      if(err) {
        res.json({no:0,msg:‘获取失败:‘+err});
      }else{
        var result = {no:1};
        result.obj=notice;
        res.json(result);
      }
    });
  }else{
    res.json({no:0,msg:id+‘不存在‘});
  }

};

 

mongoose CastError: Cast to ObjectId failed for value

标签:

原文地址:http://www.cnblogs.com/yshyee/p/4583652.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!