sac Dahal
sac Dahal

Reputation: 1241

mongodb : using update() to update and get the updated data

I want to update and get the updated data like we do { new : true } for findByIdAndUpdate in case we want updated data . How do we do that using update function.

 mBooking.update(updateDbParams.condition, updateDbParams.update, function(error, resultData) {
    if(error)
      res.json(mResponse.response(null, null, "something went wrong", null));
    else
       {
         console.log(resultData); 
       }
 });

so console.log returns;

    { ok: 1,
  nModified: 1,
  n: 1,
  opTime:
   { ts: Timestamp { _bsontype: 'Timestamp', low_: 1, high_: 1483945954 },
     t: 1 },
  electionId: 7fffffff0000000000000001 }

Upvotes: 0

Views: 828

Answers (3)

Shaishab Roy
Shaishab Roy

Reputation: 16805

You can use findOneAndUpdate with new:true option

mBooking.findOneAndUpdate(updateDbParams.condition, updateDbParams.update, {new:true}, function(error, resultData) {
    if(error)
      res.json(mResponse.response(null, null, "something went wrong", null));
    else
       {
         console.log(resultData); 
       }
 });

Upvotes: 4

QuasiFigures
QuasiFigures

Reputation: 67

The mongoose update function does not return the updated document. This is shown here.

As it explains, mongoose's findByIdAndUpdate function with { new: true } is the best option. Also shows the lengthier version of findById -> save.

Upvotes: 0

titogeo
titogeo

Reputation: 2184

You can use findAndModify of MongoDB. I am not very sure about the node driver equivalent of this.

Modifies and returns a single document. By default, the returned document does not include the modifications made on the update. To return the document with the modifications made on the update, use the new option. The findAndModify() method is a shell helper around the findAndModify command.

Upvotes: 0

Related Questions