mongoose CastError: Cast to ObjectId failed for value

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+'不存在'});
  }

};

 

posted @ 2015-06-17 16:24  yshy  阅读(5938)  评论(0编辑  收藏  举报