How to Perform Upsert in Mongoose

Tek Loon
1 min readSep 18, 2020

--

Photo by Matt Eason on Unsplash

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.

References

--

--

Tek Loon
Tek Loon

Written by Tek Loon

Coder and Writer. If you enjoy my stories— support me by https://www.buymeacoffee.com/tekloon so I can keep writing articles for the community.

No responses yet