Mongoose findByIdAndUpdate / findById返回null作为模型

在我的节点应用程序中,在后端使用mongoose,在前端使用backbone:

console.log(typeof elementid, elementid); //string 559578bb66e931bc11c02214 try { myModel.findByIdAndUpdate(elementid, {marked: true}, {upsert: false, new: true}, function (err, doc) { console.log(err); //null console.log(doc); //null }); } catch (error) { console.log(error); //not executed } 

数据库中的文件:

 { "_id" : ObjectId("559578bb66e931bc11c02214"), "marked" : false, //..more stuff here... } 

本文档的架构:

 myModelSchema = mongoose.Schema({ "marked": Boolean, //more stuff here... }); 

findById()也不返回任何文档。

但是我可以在MongoDB中search并find文件:

db.getCollection('mymodels')。find({'_ id':ObjectId('559578bb66e931bc11c02214')})

我认为这是因为id不是一个string,但用ObjectId()表示? ObjectIds是在第一次创build文档时由mongoose创build的。 所以我不明白为什么我不能通过_id来查询和查找文档。

更新:

我把upsert设置为true。 现在在数据库中创build一个新文档,如下所示:

{“_id”:“559578bb66e931bc11c02214”,“标记”:true}

该id不会被转换为ObjectId。 可能是什么原因? 它在使用相同模式和数据库设置的另一个脚本中工作…

解决scheme:

 var ObjectId = require('mongoose').Types.ObjectId; var elementid = new ObjectId(elementid); var query = {_id: elementid}; app.uiElement.findOneAndUpdate(query, {marked: true}, {upsert: false, new: true}, function (err, doc) { console.log(doc); //works now }); 

如果你知道为什么我必须在这种情况下明确地将_id转换为Object _id,请让我知道。 驱使我疯了,我浪费了几个小时在这个。 正如我所说,在另一个使用相同的mongooseconfiguration的脚本,我不需要投下_id。