解决方案 简短回答:使用 mongoose.Types.ObjectId.Mongoose(但不是 mongo)可以接受对象 ID 作为字符串并为您正确转换"它们,所以只需使用:MyClass.findById(req.params.id)但是,需要注意的是,如果 req.params.id 不是 mongo ID 字符串的有效格式,则会抛出您必须捕获的异常.所以要理解的主要令人困惑的事情是 mongoose.SchemaTypes 有你只在定义 mongoose 模式时使用的东西,而 mongoose.Types 有你在创建时使用的东西要存储在数据库中的数据对象或查询对象.所以 mongoose.Types.ObjectId("51bb793aca2ab77a3200000d") 工作,会给你一个对象,你可以存储在数据库中或在查询中使用,如果给出无效的 ID 字符串,将抛出异常.>findOne 接受一个查询对象并将单个模型实例传递给回调.而 findById 实际上是 findOne({_id: id}) (在此处查看源代码).只需 find 获取一个查询对象并将匹配模型实例的数组传递给回调.慢慢来.这很令人困惑,但我可以向您保证,此时您会感到困惑并且不会在 mongoose 中遇到错误.这是一个相当成熟的库,但需要一些时间来掌握它.我在你的代码片段中看到的另一个可疑的事情是在实例化 ChildClass 时没有使用 new.除此之外,您还需要发布您的架构代码,以便我们帮助您解决任何剩余的 CastErrors.I am new to node.js, so I have a feeling that this will be something silly that I have overlooked, but I haven't been able to find an answer that fixes my problem. What I'm trying to do is create a path that will create a new child object, add it to the parent's array of children, then return the child object to the requester. The problem that I am running into is that if I pass the string id into findById, node crashes withIf I try to pass in an ObjectId instead, I getHere is a rough outline of my code:var mongoose = require('mongoose');var Schema = mongoose.Schema;var ObjectId = Schema.ObjectId; //Have also tried Schema.Types.ObjectId, mongoose.ObjectIdmongoose.connect('mongodb://user:password@server:port/database');app.get('/myClass/:Id/childClass/create', function(request, result) { var id = new ObjectId(request.params.Id); MyClass.findById(id).exec( function(err, myClass) { if (err || !myClass) { result.send("error: " + err + "<br>" + JSON.stringify(id) || ("object '" + request.params.Id + "' not found: " + id)); return; } var child = ChildClass(); myClass.Children.addToSet(child); myClass.save(); result.send(child); });});If I execute this code with the path "/myClass/51c35e5ced18cb901d000001/childClass/create", this is the output of the code:I've tried using findOne and passing in {_id:id} instead, but this appears to be exactly what findById does. I've tried the different classes for ObjectId that I've seen listed on other sites. I've tried calling ObjectId() like a function instead of a constructor and that returns undefined. At this point, I'm running out of ideas and it doesn't seem that googling for an answer is helping. Any ideas on what I'm doing wrong?Also, like I said, I'm new to node/Mongo/Mongoose/Express, so if there is a better way to accomplish my goal, please let me know. I appreciate all feedback.EDIT:After the workaround from Peter Lyons, I googled another error that I was running into and found findByIdAndUpdate, which works as expected and does exactly what I was hoping to do. I'm still not sure why findById and findOne were giving me such issues and I'm curious to know (maybe a bug report needs to be filed), so I'll leave this open in case someone else has an answer. 解决方案 Short answer: use mongoose.Types.ObjectId.Mongoose (but not mongo) can accept object Ids as strings and "cast" them properly for you, so just use:MyClass.findById(req.params.id)However, the caveat is if req.params.id is not a valid format for a mongo ID string, that will throw an exception which you must catch.So the main confusing thing to understand is that mongoose.SchemaTypes has stuff you only use when defining mongoose schemas, and mongoose.Types has the stuff you use when creating data objects you want to store in the database or query objects. So mongoose.Types.ObjectId("51bb793aca2ab77a3200000d") works, will give you an object you can store in the database or use in queries, and will throw an exception if given an invalid ID string.findOne takes a query object and passes a single model instance to the callback. And findById is literally a wrapper of findOne({_id: id}) (see source code here). Just find takes a query object and passes an array of matching model instances to the callback.Just go slow. It's confusing but I can guarantee you you are getting confused and not hitting bugs in mongoose at this point. It's a pretty mature library, but it takes some time to get the hang of it.The other suspect thing I see in your snippet is not using new when instantiating ChildClass. Beyond that, you'll need to post your schema code in order for us to help you tract down any CastErrors that remain. 这篇关于Mongoose:CastError:Cast to ObjectId 因值“[object Object]"而失败;在路径“_id"处的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 上岸,阿里云!