Reputation: 9055
I am wondering what the best way to go about checking fields in a document before updating the document in Mongoose is. I know I can just use findOne()
and then update the fields manually then save. But this is a pain when you want to send an object with multiple fields that you want to update and the fields that you want to update could be different. So right now I am querying with findOne()
and then checking the field I want to check against, then using updateOne()
to update the document. As far as I know updateOne()
doesn't allow for checking fields beforehand. So is this the best way to go about it? It seems a bit redundant making 2 requests to the database. Also is there any side effects of having a query open while updating? Here is an example of the code I am using:
const doc = await Doc.findOne({ _id: req.body._id });
if (!doc || doc.method === 'foo') return res.status(400).end();
Doc.updateOne({ _id: req.body._id }, req.body.bar);
Like I said I can't really find any good answers to this question on stackoverflow and the mongoose documentation doesn't seem to be any help either.
Upvotes: 1
Views: 988
Reputation: 11975
You can use findOneAndUpdate(). This method:
Finds a matching document, updates it according to the update arg, passing any options, and returns the found document (if any) to the callback.
So in your case, you just need to add your condition to the query, if this method doesn't find any match, it will not update anything.
Example:
await Doc.findOneAndUpdate({ _id: req.body._id, method: {$ne: "foo"} }, req.body.bar);
Upvotes: 1