qazxswedc
qazxswedc

Reputation: 63

Unable to update the database using findAndModify

I'm using Node.js with mongodb.

    var mongo = require("mongodb").MongoClient;
    var url = process.env.MLAB_URI;

    mongo.connect(url, function (err, db) {
      if (err) {
      console.log('Unable to connect to the mongoDB server. Error:', err);
      } else {
    //HURRAY!! We are connected. :)
    console.log('Connection established');
    var sequence = db.collection('sequence')

    //Find and modify the sequence counter.
    var obj = sequence.findAndModify({
      query: {_id: 1},
      update: { $inc: {seq: 1}},
      new: true
    });

    console.log(obj);

    sequence.find({_id:1}).toArray(function(err,res){
      if(err)
        console.log(err);
      else
        console.log(res)
    });

     db.close();
  }
});

But the above code is not updating the database and the output of obj that is returned is Promise { <pending> } . The complete output is

Connection established
Promise { <pending> }
[ { _id: 1, seq: 0 } ]

I need to update the value and retrieve the object . Is there any way to do that? Thanks in advance!

Upvotes: 1

Views: 323

Answers (2)

Omer Demircan
Omer Demircan

Reputation: 16

change to

var obj = sequence.findOneAndModify({
  _id: 1,
  update: { $inc: {seq: 1}},
  upsert: true
});

Upvotes: 0

notionquest
notionquest

Reputation: 39226

Please change the findAndModify as mentioned below.

var obj = sequence.findAndModify(
  {_id: 1},
  {},
  {  $inc: {"seq": 1}},      
  {new:true, upsert:true}
);

Second option to avoid promise:-

Comment the console.log(obj);

var obj = sequence.findAndModify(
  {_id: "1"},
  {},
  {  $inc: {"seq": 1}},      
  {new:true, upsert:true}, function (err, doc) {
    if(err)
    console.log(err);
  else
    console.log(doc);
  }
);

You are referring the Mongo shell version and try implementing the same using NodeJS version. The NodeJS findAndModify version is little different.

In order to get the old value of seq, you can set the new flag to false and doc.value.seq gives you the old value (i.e. value before update).

sequence.findAndModify(
  {_id: "1"},
  {},
  {  $inc: {"seq": 1}},      
  {new:false, upsert:true}, function (err, doc) {
    if(err)
    console.log(err);
  else {

    console.log(doc);
    console.log(doc.value.seq);
  }
  });

Upvotes: 2

Related Questions