我想要获取更新的文档。这是我的原始代码,它成功更新但不返回文档。
collection.update({ "code": req.body.code },{$set: req.body.updatedFields}, function(err, results) {
res.send({error: err, affected: results});
db.close();
});
我用的是toArray
函数,但这给出了错误“在没有提供回调的情况下无法使用 writeConcern”:
collection.update({ "code": req.body.code },{$set: req.body.updatedFields}).toArray( function(err, results) {
res.send({error: err, affected: results});
db.close();
});
有任何想法吗?
collection.update() https://mongodb.github.io/node-mongodb-native/3.6/api/Collection.html#update只会向其自己的回调报告受影响的文档数量。
要在修改时检索文档,您可以使用collection.findOneAndUpdate() https://mongodb.github.io/node-mongodb-native/3.6/api/Collection.html#findOneAndUpdate相反(以前.findAndModify() https://mongodb.github.io/node-mongodb-native/3.6/api/Collection.html#findAndModify).
collection.findOneAndUpdate(
{ "code": req.body.code },
{ $set: req.body.updatedFields },
{ returnOriginal: false },
function (err, documents) {
res.send({ error: err, affected: documents });
db.close();
}
);
The returnOriginal
选项(或new
与 Mongoose)允许您指定将找到的文档的哪个版本(原始[默认]或更新)传递给回调。
returnOriginal
已在版本中弃用3.6
. Use returnDocument: "before" | "after"
对于版本3.6
然后。
免责声明:此答案目前指的是 Node.js 驱动程序3.6版本 https://mongodb.github.io/node-mongodb-native/3.6/api/。随着新版本的发布,请检查其文档以获取可能的新弃用警告和推荐的替代方案。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)