我正在尝试使用 update option MongoDB 中的 { fullResult: true }
选项。
collection.update(query, payload, { fullResult: true }, function(err, result) {
console.log(result);
});
虽然它确实改变了结果的值,但我不会取回文档。相反,我回来了:
[ { updatedExisting: true,
n: 1,
lastOp: { _bsontype: 'Timestamp', low_: 1, high_: 1403025407 },
connectionId: 510045,
err: null,
ok: 1 } ]
为了回到更新后的文档,我还应该做些什么吗?
最佳答案
使用findAndModify
:
collection.findAndModify(query,[['_id',1]],payload,{new:true},function(err,result) {
if ( err ) {
console.warn(err);
} else {
console.log(result);
}
});
当设置为 true
时,new
选项将返回更新的 文档。如果设置为 false
,它将返回 更新之前的旧文档。
findAndModify
还需要一个 sort 参数。如果排序不重要,那么按 _id 排序就可以了,但请尝试按索引排序。
将 fullResult
与 update
一起使用并没有按照您的想法进行。我同意,文档有点困惑。让 Node.js 驱动程序源代码在 /lib/mongodb/collection/core.js:568-572 上说明一切。
568 if(fullResult) return callback(null, result);
569 // Backward compatibility format
570 var r = backWardsCompatibiltyResults(result, 'update');
571 // Return the results for a whole batch
572 callback(null, r.n, r)
无论是否使用fullResult
,都会返回result
对象而不是文档列表。 result
对象是通过 db.command
从原始数据库命令返回的内容。在使用 fullResult
的情况下,它将返回未修改的原始结果对象 - 但仍然不是文档。
关于node.js - 如何在 Node 中的 MongoDB 更新中返回完整文档,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24269827/