Four_lo
Four_lo

Reputation: 1150

Nodejs, MongoDB - Determine if Document in Collection was Updated or Inserted

I am calling the mongoDB update function with {upsert:true} to insert a new document if the given _id does not exist. I would like to determine if the document was inserted or update. Much like this question I found using java but only using Nodejs.

how to check if an document is updated or inserted in MongoDB

Here is my DB call.

app.post('/mongoSubmit', function(req, res) {

console.log("This is the req.body" + JSON.stringify(req.body, null, 4));

var updateCustomer = function(db, callback){

    db.collection('customers1').update(
        {_id:req.body.email},

            { first: req.body.firstName,
              last: req.body.lastName,
              phone: req.body.phone,
              email: req.body.email,
              subjectIndex: req.body.subject,
              messageIndex: req.body.message
            },

        { upsert: true},
         function(err, result){
            if(err){console.log("database error" + err)}
            callback(result);
        }
    );
}

MongoClient.connect(url, function(err, db){
    updateCustomer(db, function(result){

    console.log("these are the results" + JSON.stringify(result, null, 4));

/*
** Return Either
*
these are the results{
    "ok": 1,
    "nModified": 0,
    "n": 1,
    "upserted": [
        {
            "index": 0,
            "_id": "[email protected]"
        }
    ]
}

/*
*
* or

    these are the results{
    "ok": 1,
    "nModified": 1,
    "n": 1
}

//BUT  *************** Problem using this Value *********************
    console.log("this is the value of Modified" + result.nModified);

/*
** Returns undefined
*/


            if(result.nModified == 1){
                console.log("Updated document");
            }
            else{
                console.log("Inserted document");
            }

        db.close(); 
        res.render('applications', {
            title:"Title"
        });
    });
});

});

I have also tried for test doing

    if(result.hasOwnProperty('upserted'){
        //log an Insert
    if(result.upserted == true {
        //log an Insert
    if(result.nModified == 1){
        // log an update
    if(result.nModified == true){
        //log an update

and also adding upserted as a parameter to the callback which I found from a different forum.

function(err, result, upserted){
   //callback function
   //upserted was undefined
})

My result is confusing. How I could log an object with a property value but when I try to log that specific property it comes up undefined?

Could anyone explain why this might happen in javascript?

or

Suggest another solution for determining if a document in a collection was updated or inserted?



Thank You

Upvotes: 3

Views: 2460

Answers (1)

Blakes Seven
Blakes Seven

Reputation: 50406

The result is a structure that contatins it's own property "result" which has the sub-properties. So you need to inspect at the right level:

var async = require('async'),
    mongodb = require('mongodb'),
    MongoClient = mongodb.MongoClient;


MongoClient.connect('mongodb://localhost/test',function(err,db) {

  db.collection('uptest').update(
    { "a": 1 },
    { "$set": { "b": 2 } },
    { "upsert": true },
    function(err,result) {
      if (err) throw err;

      if (result.result.hasOwnProperty('upserted') ) {
        console.log( JSON.stringify( result.result.upserted,  undefined, 2 ) );
      }

      console.log( "matched: %d, modified: %d",
          result.result.n,
          result.result.nModified
      );
    }
  );

});

On a first run you will get the "array" of "upserted" like this:

[
  {
    "index": 0,
    "_id": "55a4c3cfbe78f212535e2f6a"
  }
]
matched: 1, modified: 0

On a second run with the same values then nothing is added or modified:

matched: 1, modified: 0

Change the value of "b" and "modified" is counted since the data actually changed.

Upvotes: 4

Related Questions