在MongoDB中获取更新的文档 [英] Get the updated document in MongoDB
问题描述
我需要获取更新文档的_id
(Mongo ObjectID).为此,我想获取更新的文档.我怎么才能得到它?
I need to get the _id
(the Mongo ObjectID) of updated document. For this I want to get the updated document. How can I get it?
我尝试过:
...
collection.update(oldData, newData, function(err, doc) {
console.log(docs); // This prints "1" in console. So, it's not a document.
if (err) { return callback(err); }
callback(null, doc);
});
...
我可以不通过newData/oldData查找文档而得到它吗?
Can I get it without finding a document by newData/oldData?
推荐答案
Instead of using .update()
, I think you want to use .findAndModify()
.
一个更新可以更新多个文档,其回调的第二个参数是更新的文档数(在您的情况下为1).
An update can update multiple documents, and the second argument of its callback is the number of updated documents (in your case, 1).
使用findAndModify
,您可以精确地更新一个文档(阅读与update
完全不同的文档),并将更新后的文档传递给回调函数.
With findAndModify
, you can update exactly one document (read the documentation on exactly how it differs from update
), and the updated document will be passed to the callback function.
这篇关于在MongoDB中获取更新的文档的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!