Forever Youth
Forever Youth

Reputation: 175

Mongoose findOneAndUpdate return not updated model

I've 1 little issue. I'm trying update model by findOneAndUpdate method. And this method works unexpected - method update model in DB but return old model (before update)

try {
  const updatedLanding = await Landing.findOneAndUpdate({key: req.body.key}, {
      $set: {
        name: req.body.name,

      }
    },
  ).exec((err, result) => {
    if (err) {
      res.status(422).send({error: err});
      return
    }
    res.send({response: result})
  });
}
catch (e) {
  res.status(400).send(e)
}

Upvotes: 1

Views: 502

Answers (2)

Kiran Ghatage
Kiran Ghatage

Reputation: 407

If you update document using findOneAndUpdate() hook, you'll get the old document unless you specify { new: true }

Upvotes: 1

Mehrnaz.sa
Mehrnaz.sa

Reputation: 386

in mongoose query, findOneAndUpdate returns the old record that has been updated, not the updated record, the record has actually been updated, but you can not get the updated result as the query returns the old one by default, if you want to see the updated record you have to issue another query to find the record and get its updated data.

Upvotes: 1

Related Questions