0

I have the following code:

 Something.findByIdAndUpdate(
    req.query.id,
    { $inc: { available: -1 } },
    { new: true, useFindAndModify: false },
    (err, book) => {
  );
});

I want to update the available field only if it is greater than 0. I could look for the item check if its field is bigger than 0 and then if it, look for it again and update it. Is there a way to do this using only a function?

Ovidiu Firescu
  • 385
  • 3
  • 11
  • 2
    You can use [findOneAndUpdate()](https://mongoosejs.com/docs/tutorials/findoneandupdate.html), match conditions would be `{ _id: req.query.id, available: { $gt: 0 } }` – turivishal Nov 21 '20 at 09:20
  • You're right this will do exactly what I wanted, I thought there may be a way with ```findByIdAndUpdate```. Thanks you – Ovidiu Firescu Nov 21 '20 at 09:21

0 Answers0