Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

mongoose to determine update-upsert is doing insert or update

I want to test if "upsert" option for updating is woking fine. So I "upsert" an object into mongodb twice with same key. However it didn't show inserted message. Was I missing something ?

(mongodb : v2.6.3; mongoose : 3.8.15)

Member.findOneAndRemove({user_id: 1},
    function (err, doc) {
        if (!err) onsole.log(doc ? 'deleted' : 'not found');
}); // -> deleted, make sure user_id = 1 doesn't exist

Member.update({user_id: 1}, 
    {$set: {name: "name1"}}, 
    {upsert: true, new: false}, // new : false, so that I can detect original doc is null then know it's a new one.
    function (err, doc) {
    if (!err) {
        console.log(doc ? 'updated' : 'inserted')
    }
}); // -> updated ? But it shoule be inserted, right ?

Member.update({user_id: 1}, 
    {$set: {name: "name2"}}, 
    {upsert: true, new: false},
    function (err, doc) {
    if (!err) {
        console.log(doc ? 'updated' : 'inserted')
    }
}); // -> updated, yes, no problem.

Thank you for any hint.

============ answer =============

Use .findOneAndUpdate instead of .update ! Moreover, make sure option is {upsert: true, new: false}, so that the callback's 2nd parameter(doc) could be original document in case.

like image 409
nwpie Avatar asked Dec 20 '22 09:12

nwpie


1 Answers

The .update() method in mongoose takes three arguments to the callback, being err, the numAffected, and a raw response. Use the "raw" object to see what happened:

Member.update({user_id : 1}, 
    {$set : {name:"name1"}}, 
    {upsert : true }, 
    function (err, numAffected, raw) {
    if (!err) {
        console.log(raw)
    }
});

You'll see a structure like this:

{ ok: true,
  n: 1,
  updatedExisting: false,
  upserted: [ { index: 0, _id: 5456fc7738209001a6b5e1be } ] }

So there is always the n and 'updatedExistingkeys available, where the second is false on upserts and true otherwise.upsertedwill contain the_id` values of any new documents created.

As for n or the "numAffected", this is basically always 1 where a document was matched under the legacy write concern responses.

You can see the new WriteResult response in MongoDB 2.6 and above using the Bulk Operations form:

var bulk = Member.collection.initializeOrderedBulkOp();
bulk.find({user_id : 1}.upsert().update({$set : {name:"name1"}});
bulk.execute(err,result) {
   console.log( JSON.stringify( result, undefined, 2 ) );
}

Which on a first iteration you get something like this:

{
  "ok": 1,
  "writeErrors": [],
  "writeConcernErrors": [],
  "nInserted": 0,
  "nUpserted": 1,
  "nMatched": 0,
  "nModified": 0,
  "nRemoved": 0,
  "upserted": [
    {
      "index": 0,
      "_id": "5456fff138209001a6b5e1c0"
    }
  ]
}

And a second with the same parameters like this:

{
  "ok": 1,
  "writeErrors": [],
  "writeConcernErrors": [],
  "nInserted": 0,
  "nUpserted": 0,
  "nMatched": 1,
  "nModified": 0,
  "nRemoved": 0,
  "upserted": []
}

And the document would only be marked as "modified" where something was actually changed.

So at any rate, .update() operations do not return the modified document or the original document. That is the .findOneAndUpdate() method, a mongoose wrapper around the basic .findAndModify() which performs an atomic operation. The .update() methods are typically meant for bulk operations and as such do not return document content.

like image 179
Neil Lunn Avatar answered Jan 13 '23 20:01

Neil Lunn