0

In MongoDB (using node.js) I want to update a record and then fetch the returned record.

Can I do this atomically at all?

My searching suggested I could use findOneAndUpdate, however my testing with this reveals that it does it in the order that it says, so the "find" part of it is returning the record found before the update.

> db.demo.insert({ id: 1, data: "abc" })
WriteResult({ "nInserted" : 1 })
> db.demo.findOneAndUpdate( { id: 1}, { $set: { data: "xyz" } } )
{ "_id" : ObjectId("5ae82c1d53d7ae2de3ffbcea"), "id" : 1, "data" : "abc" }

How do I find the record after the update?

0

1 Answer 1

3

from mongodb documentations:

db.collection.findOneAndUpdate(
    filter,
   update,
   {
     projection: <document>,
     sort: <document>,
     maxTimeMS: <number>,
     upsert: <boolean>,
     returnNewDocument: <boolean>,
     collation: <document>,
     arrayFilters: [ <filterdocument1>, ... ]
   }
)

note: returnNewDocument should be the option to control whether to receive new or old document.

edit: check this question if you use mongoose

Sign up to request clarification or add additional context in comments.

1 Comment

Note that when using node, instead of returnNewDocument: true it should be returnOriginal: false

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.