1

following the official manual,

db.students2.findOneAndUpdate(
   { _id : 1 },
   [ { $set: { "total" : { $sum: "$grades.grade" } } } ],  // The $set stage is an alias for ``$addFields`` stage
   { returnNewDocument: true }
)

My implementation,

const usersCollection = db().collection("users"); // db() is exposed via a module

usersCollection.findOneAndUpdate(
   { _id : new ObjectID (this.data._id)},
   { $set: { 
           total : this.data.updatedTotal
        }
    } ,
   { returnNewDocument: true }
)

despite the { returnNewDocument: true } option, it still returns the old document

But, when I query the collection again,

usersCollection.findOne({_id: new ObjectID()}); // returns the updated document

it returns the updated document. Which means that the db.collection.findOneAndUpdate() worked.

the problem is, it's not returning the updated document, despite the { returnNewDocument: true } option .

Why is that ?

Rahul Dahal
  • 152
  • 1
  • 12

4 Answers4

1

For mongoose to return the new document, you need to add { new: true } to the query.

I would give this as shot:

usersCollection.findOneAndUpdate(
   { _id : new ObjectID (this.data._id) },
   { $set: { total : this.data.updatedTotal } },
   { new: true }
)
1

To return it you need to add

{returnOriginal: false}

Always check the Node JS MongoDB API

Minsky
  • 2,277
  • 10
  • 19
1

Node mongodb driver: returnOriginal was Deprecated, use returnDocument with "before" or "after" instead.

{returnDocument: 'after'}
Elect2
  • 1,349
  • 2
  • 12
  • 22
-1

I solved it.

Since I am using the native mongodb driver,

we'll want to use {returnOriginal: false} instead of {new: true}.

Rahul Dahal
  • 152
  • 1
  • 12