This post discussed how you can perform upsert with Mongoose. Upsert is the combination of insert and update, if it is a new record, it will perform the CREATE operation while if the existing record found, it will UPDATE on the existing record.
Without further ado, let’s start.
Upsert in Mongoose
Learning is enhanced with a real case study. Imagine that you are the Backend Developer for a job portal. Here is the given requirement:
- Candidates are able to add new working experience and edit their existing working experiences.
We can easily use the API provided by Mongoose findOneAndUpdate
to perform the upsert by simply setting the option { upsert: true }
. Refer to the code below.
Conclusion
Here are the key points of this article.
- We can perform upsert using
findOneAndUpdate
in Mongoose. - By simply setting option
{ upsert: true }
, we can have both update and insert functions.
Thank you for reading. See you in the next article.
The original article was published on my blog.