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

dor*_*emi 8 mongodb node.js

我正在尝试使用MongoDB中的更新选项 { fullResult: true }选项.

collection.update(query, payload, { fullResult: true }, function(err, result) {
  console.log(result);
});
Run Code Online (Sandbox Code Playgroud)

虽然它确实改变了结果的价值,但我没有收回文件.相反,我回来了:

[ { updatedExisting: true,
    n: 1,
    lastOp: { _bsontype: 'Timestamp', low_: 1, high_: 1403025407 },
    connectionId: 510045,
    err: null,
    ok: 1 } ]
Run Code Online (Sandbox Code Playgroud)

为了回到更新的文档,还有什么我应该做的吗?

zam*_*uts 12

用途findAndModify:

collection.findAndModify(query,[['_id',1]],payload,{new:true},function(err,result) {
    if ( err ) {
        console.warn(err);
    } else {
        console.log(result);
    }
});
Run Code Online (Sandbox Code Playgroud)

设置new为时,该选项将返回更新的文档true.如果设置为false,则会更新返回旧文档.

findAndModify还需要一个排序参数.如果排序不重要,那么在_id上排序就可以了,但是尝试对索引的内容进行排序.


使用fullResultwith 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)
Run Code Online (Sandbox Code Playgroud)

无论是否fullResult使用,result都返回对象而不是文档列表.该result对象是从原始db命令返回的内容db.command.在这种情况下,当fullResult 使用时,它会返回原始的未经修改的结果对象-但仍然没有文档.