如何在Node中的MongoDB更新中返回完整的文档

我试图在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); } }); 

new选项将设置为true时返回更新的文档。 如果设置为false ,它将更新之前返回旧文档。

findAndModify也需要一个sorting参数。 如果sorting不重要,那么在_id上sorting会很好,但是尝试对索引的东西进行sorting。


update中使用fullResult并不符合您的想法。 我同意,文档有点混乱。 让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, rn, r) 

无论是否使用了fullResult ,都会返回result对象而不是文档列表。 result对象是通过db.command从raw db命令返回的db.command 。 在使用fullResult的情况下,它将返回未经修改的原始结果对象 – 但仍然不是文档。