chad512
chad512

Reputation: 87

Idiomatic way to update a document after finding it?

I'm new to Mongoose and have am trying to do something like this:

  1. Get a document
  2. Do some stuff
  3. Update and save the document

I'm able to get this working as follows:

const doc = await Foo.findById(id)
// Do stuff
const updatedDoc = await Foo.findOneAndUpdate(
      { _id: id},
      { $inc: { counter: 1 },
      { new: true }
)

But this doesn't feel like it's the right way to do it since I have to find the document twice. What is the idiomatic way to do this?

Upvotes: 0

Views: 34

Answers (1)

Hakim Baheddi
Hakim Baheddi

Reputation: 287

you can do like

const doc = await Foo.findById(id) 
// Do stuff
doc.counter++
doc.save()

Upvotes: 1

Related Questions