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?

Kris Randall
  • 686
  • 1
  • 7
  • 12

1 Answers1

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

Ashar Dweedar
  • 613
  • 6
  • 16