Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to return full document in a MongoDB update in Node

I'm trying to use the update option { fullResult: true } option in a MongoDB.

collection.update(query, payload, { fullResult: true }, function(err, result) {
  console.log(result);
});

While it does change the value of result, I'm not getting back the document. Instead, I'm getting back:

[ { updatedExisting: true,
    n: 1,
    lastOp: { _bsontype: 'Timestamp', low_: 1, high_: 1403025407 },
    connectionId: 510045,
    err: null,
    ok: 1 } ]

Is there something else I should be doing in order to get back to the updated document?

like image 288
doremi Avatar asked Jun 17 '14 17:06

doremi


1 Answers

Use findAndModify:

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

The new option will return the updated document when set to true. If set to false, it will return the old document before update.

findAndModify also requires a sort parameter. If sorting is not important, then sorting on _id will be fine, but try to sort on something indexed.


Using fullResult with update does not do what you think. I agree, the docs are a bit confusing. Let the Node.js driver source speak for itself at /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)

Regardless if fullResult is used, the result object is returned rather than a list of documents. The result object is what is returned from the raw db command via db.command. In the case when fullResult is used, it will return the raw unmodified result object - but still not documents.

like image 192
zamnuts Avatar answered Nov 10 '22 00:11

zamnuts