'How to get matchedId or upsertedId with findOneAndUpdate or updateOne in MongoDB in NodeJS?
For both of those functions upsert is set to true.
So updateOne returns upsertedId if no document matched the query, but if one document matches it does not return the id of the document that did (only matchedCount = 1).
And findOneAndUpdate with the newDocument option set to true will return the id of the updated document if it already exists, but if it does not it will return a lastErrorObject which contains the id of the upserted document but I do not like that it is an error.
I'd like to update a document if it already exists or create a new one if it does not, and retrieve the id of the updated/created document without it being in an error object. Is it possible with a single function?
Solution 1:[1]
So for findOneAndUpdate options returnNewDocument = true and returnDocument = "after" behave differently despite returnDocument supposedly being an alternative to returnNewDocument.
With returnDocument = "after", findOneAndUpdate will return an object that contains the document no matter if it is upserted or updated (so result.value._id will always give the id of the document).
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | François MENTEC |
