在Mongodb中更新和返回文档
我想获得更新的文件。 这是我的原始代码,它成功更新,但不返回文档。
collection.update({ "code": req.body.code },{$set: req.body.updatedFields}, function(err, results) { res.send({error: err, affected: results}); db.close(); });
我使用了Array函数,但是这给了错误“不能使用writeConcern没有提供的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()
只会报告受影响的文档数量到自己的callback。
要在修改时检索文档,可以使用collection.findOneAndUpdate()
(以前的.findAndModify()
)。
collection.findOneAndUpdate( { "code": req.body.code }, { $set: req.body.updatedFields }, { new: true }, function (err, documents) { res.send({ error: err, affected: documents }); db.close(); } );
请注意,它将修改所有匹配的文件,其中.update()
期望multi: true
来执行相同的操作。
注意:当前指的是版本2.2以上的Node.js驱动程序。 对于将来的版本,检查文档中的弃用警告,并使用推荐的替代方法。
找不到任何方法来更新许多文件 ,并返回文档中的修改logging,所以我提出了一个解决方法。
至less有一个我可以用下面的方法find的错误是,你不能告诉文档是否被修改或已经有你正在使用的值:
function findAndUpdateMany(filter, updateOptions) { return collection.find(filter).project({_id: 1}).toArray() .then(function(matchingIds) { filter = {_id: {$in: matchingIds}} return collection.updateMany(filter, updateOptions) }).then(function() { return collection.find(filter).toArray() }) }
检出WriteResult对象:
http://docs.mongodb.org/manual/reference/method/db.collection.update/#writeresults-update
WriteResult result = collection.update({ "code": req.body.code },{$set: req.body.updatedFields}, function(err, results) { res.send({error: err, affected: results}); db.close(); });
结果应该是这样的:
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
如果您想要更新的结果,请使用主键执行另一个查询。