值XXX的猫鼬错误转换为ObjectId失败了吗

值XXX的猫鼬错误转换为ObjectId失败了吗

本文介绍了在路径"_id"中,值XXX的猫鼬错误转换为ObjectId失败了吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

/customers/41224d776a326fb40f000001发送请求并且不存在带有_id 41224d776a326fb40f000001的文档时,docnull,而我返回的是404:

When sending a request to /customers/41224d776a326fb40f000001 and a document with _id 41224d776a326fb40f000001 does not exist, doc is null and I'm returning a 404:

  Controller.prototype.show = function(id, res) {
    this.model.findById(id, function(err, doc) {
      if (err) {
        throw err;
      }
      if (!doc) {
        res.send(404);
      }
      return res.send(doc);
    });
  };

但是,当_id与Mongoose期望的格式"(我想)不符时(例如,对于GET /customers/foo),将返回一个奇怪的错误:

However, when _id does not match what Mongoose expects as "format" (I suppose) for example with GET /customers/foo a strange error is returned:

那这是什么错误?

推荐答案

猫鼬的findById方法将id参数强制转换为模型的_id字段的类型,以便其可以正确查询匹配的文档.这是一个ObjectId,但"foo"不是有效的ObjectId,因此强制转换失败.

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 "foo" is not a valid ObjectId so the cast fails.

41224d776a326fb40f000001不会发生这种情况,因为该字符串是有效的ObjectId.

This doesn't happen with 41224d776a326fb40f000001 because that string is a valid ObjectId.

解决此问题的一种方法是在您的findById调用之前添加检查,以查看id是有效的ObjectId还是这样:

One way to resolve this is to add a check prior to your findById call to see if id is a valid ObjectId or not like so:

if (id.match(/^[0-9a-fA-F]{24}$/)) {
  // Yes, it's a valid ObjectId, proceed with `findById` call.
}

这篇关于在路径"_id"中,值XXX的猫鼬错误转换为ObjectId失败了吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-24 19:07