Node.js Mongoose更改文档\u id保存/更新时
一个简单的例子: 为什么在我推送更新时,Mongoose会更改/升级文档的_id字段? 这是故意的行为吗 谢谢 这是我在PUT路由中使用的更新,它成功地返回了更新后的模型,但不幸的是带有一个新的文档idNode.js Mongoose更改文档\u id保存/更新时,node.js,mongodb,mongoose,Node.js,Mongodb,Mongoose,一个简单的例子: 为什么在我推送更新时,Mongoose会更改/升级文档的_id字段? 这是故意的行为吗 谢谢 这是我在PUT路由中使用的更新,它成功地返回了更新后的模型,但不幸的是带有一个新的文档id Document.findById(req.params.doc_id, function (err, doc) { if (err) res.send(err) // Do some subdoc stuff here … doc.save(func
Document.findById(req.params.doc_id, function (err, doc) {
if (err)
res.send(err)
// Do some subdoc stuff here …
doc.save(function (err) {
if (!err) {
console.log('Success!');
res.json(doc);
} else {
console.log(err);
}
});
});
好的,问题解决了:
我记录了错误的_id(doh!)猫鼬文档
建议使用update
或findOne
例:
或
后来,我还发现一些文档中建议的findById更新似乎是最新的,请检查您正在使用的版本,并再次检查您在函数中使用的两次doc
。您还可以检查mongoDB,查看是否保存了多条记录
db.documents.find( {} )
你确定这实际上是一个更新吗?它不应该改变_id。用一些代码会更容易理解。对不起,有人投票否决了你,伙计,不是我。嗨。2.7已经过时了,我用了3.8.*的猫鼬。至于保存和更新,这实际上取决于:我主要在save上使用Mongoose中间件(pre/post)来散列密码。这篇文章很好地描述了这一点:
Model.findOne({ "_id": req.params.doc_id }, function (err, doc){
doc.name = 'jason borne';
doc.save();
// here you could use your save instead, but try not to use the doc again
// it is confusing
// doc.save(function (err, documentSaved, numberAffected) {
// if (!err) {
// console.log('Success!');
// res.json(documentSaved);
// } else {
// console.log(err);
// }
// });
});
db.documents.find( {} )