mongodb 对于路径“_id”处的值 XXX,Mongoose 错误 Cast to ObjectId 失败是什么?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14940660/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 13:03:29  来源:igfitidea点击:

What's Mongoose error Cast to ObjectId failed for value XXX at path "_id"?

mongodbmongoose

提问by gremo

When sending a request to /customers/41224d776a326fb40f000001and a document with _id41224d776a326fb40f000001does not exist, docis nulland I'm returning a 404:

当发送一个请求/customers/41224d776a326fb40f000001,并用文件_id41224d776a326fb40f000001不存在,docnull和我返回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);
    });
  };

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

但是,当_id与 Mongoose 期望的“格式”(我想)不匹配时,例如GET /customers/foo返回一个奇怪的错误:

CastError: Cast to ObjectId failed for value "foo" at path "_id".

CastError:对于路径“_id”处的值“foo”,强制转换为 ObjectId 失败。

So what's this error?

那么这个错误是什么?

回答by JohnnyHK

Mongoose's findByIdmethod casts the idparameter to the type of the model's _idfield 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.

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

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

这不会发生,41224d776a326fb40f000001因为该字符串是有效的 ObjectId。

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

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

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

回答by xpepermint

Use existing functions for checking ObjectID.

使用现有函数检查 ObjectID。

var mongoose = require('mongoose');
mongoose.Types.ObjectId.isValid('your id here');

回答by gustavohenke

Are you parsing that string as ObjectId?

您是否将该字符串解析为ObjectId

Here in my application, what I do is:

在我的应用程序中,我所做的是:

ObjectId.fromString( myObjectIdString );

回答by Ryan Dhungel

I had to move my routes on top of other routes that are catching the route parameters:

我不得不将我的路线移动到捕获路线参数的其他路线之上:

// require express and express router

const express = require("express");
const router = express.Router();

// move this `/post/like` route on top

router.put("/post/like", requireSignin, like);

// keep the route with route parameter `/:postId` below regular routes

router.get("/post/:postId", singlePost);

回答by s.babar

I have the same issue I add
_id: String .in schema then it start work

我有同样的问题,我添加了
_id: String .in schema 然后它开始工作

回答by yogesh agrawal

 if(mongoose.Types.ObjectId.isValid(userId.id)) {
        User.findById(userId.id,function (err, doc) {
            if(err) {
                reject(err);
            } else if(doc) {
                resolve({success:true,data:doc});
            } else {
                reject({success:false,data:"no data exist for this id"})

            }
        });
        } else {
            reject({success:"false",data:"Please provide correct id"});
        }

best is to check validity

最好是检查有效性

回答by Crowdpleasr

In my case, I had to add _id: Objectinto my Schema, and then everything worked fine.

就我而言,我必须添加_id: Object到我的架构中,然后一切正常。

回答by Brajalal Pal

//Use following to check if the id is a valid ObjectId?

var valid = mongoose.Types.ObjectId.isValid(req.params.id);
if(valid)
{
  //process your code here
} else {
  //the id is not a valid ObjectId
}

回答by ZEE

You can also use ObjectId.isValid like the following :

您还可以使用 ObjectId.isValid 如下:

if (!ObjectId.isValid(userId)) return Error({ status: 422 })

回答by think-serious

As of Nov 19, 2019

截至 2019 年 11 月 19 日

You can use isValidObjectId(id)from mongoose version 5.7.12

您可以isValidObjectId(id)从 mongoose 版本 5.7.12 开始使用

https://mongoosejs.com/docs/api/mongoose.html#mongoose_Mongoose-isValidObjectId

https://mongoosejs.com/docs/api/mongoose.html#mongoose_Mongoose-isValidObjectId