在 Mongodb 中更新和返回文档 [英] Update And Return Document In Mongodb
问题描述
我想获取更新的文档.这是我的原始代码,它成功更新但不返回文档.
I want to get updated documents. This is my original code and it successfully updates but doesn't return the document.
collection.update({ "code": req.body.code },{$set: req.body.updatedFields}, function(err, results) {
res.send({error: err, affected: results});
db.close();
});
我使用了 toArray
函数,但这给出了错误没有提供的回调就不能使用 writeConcern":
I used the toArray
function, but this gave the error "Cannot use a writeConcern without a provided callback":
collection.update({ "code": req.body.code },{$set: req.body.updatedFields}).toArray( function(err, results) {
res.send({error: err, affected: results});
db.close();
});
有什么想法吗?
推荐答案
collection.update()
只会将受影响的文档数量报告给它自己的回调.
collection.update()
will only report the number of documents that were affected to its own callback.
修改时检索文档,可以使用collection.findOneAndUpdate()
代替(以前是 .findAndModify()
).
To retrieve the documents while modifying, you can use collection.findOneAndUpdate()
instead (formerly .findAndModify()
).
collection.findOneAndUpdate(
{ "code": req.body.code },
{ $set: req.body.updatedFields },
{ returnOriginal: false },
function (err, documents) {
res.send({ error: err, affected: documents });
db.close();
}
);
returnOriginal
选项(或 new
与 Mongoose)允许您指定将找到的文档的哪个版本(原始 [默认] 或更新)传递给回调.
The returnOriginal
option (or new
with Mongoose) lets you specify which version of a found document (original [default] or updated) is passed to the callback.
returnDocument: before";|after"
适用于 3.6.9
版本.
免责声明:此答案目前指的是 版本的 Node.js 驱动程序3.6.随着新版本的发布,请查看他们的文档以了解可能的新弃用警告和推荐的替代方案.
Disclaimer: This answer currently refers to the Node.js Driver as of version 3.6. As new versions are released, check their documentation for possibly new deprecation warnings and recommended alternatives.
这篇关于在 Mongodb 中更新和返回文档的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!