How to upsert a document in Mongoose

In MongoDB, an upsert is an update query that inserts a new document if no document matches the given filter.

To upsert a document in Mongoose, you need to set the upsert option to true in updateOne() method as shown below:

const mongoose = require('mongoose')

const User = mongoose.model('User', { name: String, email: String })

await User.updateOne(
  {
    email: 'john@example.com'
  },
  {
    name: 'John Doe',
    email: 'john@example.com'
  },
  {
    upsert: true
  }
)

To get the upserted document, you need to use the findOneAndUpdate() function instead:

const user = await User.findOneAndUpdate(
  {
    email: 'john@example.com'
  },
  {
    name: 'John Doe',
    email: 'john@example.com'
  },
  {
    upsert: true,
    new: true
  }
)

Note that Mongoose will only inert at most one document even if you use updateMany() with upsert.

To upsert multiple documents at once, you need to use the bulkWrite() method as shown below:

const res = await User.bulkWrite([
  {
    updateOne: {
      filter: { email: 'john@exmaple.com' },
      update: { name: 'John Doe', email: 'john@exmaple.com' },
      upsert: true
    }
  },
  {
    updateOne: {
      filter: { email: 'alex@exmaple.com' },
      update: { name: 'Alex Lee', email: 'alex@exmaple.com' },
      upsert: true
    }
  }
])

res.upsertedCount // Number of upserted documents

✌️ Like this article? Follow me on Twitter and LinkedIn. You can also subscribe to RSS Feed.

You might also like...

Digital Ocean

The simplest cloud platform for developers & teams. Start with a $200 free credit.

Buy me a coffee ☕

If you enjoy reading my articles and want to help me out paying bills, please consider buying me a coffee ($5) or two ($10). I will be highly grateful to you ✌️

Enter the number of coffees below:

✨ Learn to build modern web applications using JavaScript and Spring Boot

I started this blog as a place to share everything I have learned in the last decade. I write about modern JavaScript, Node.js, Spring Boot, core Java, RESTful APIs, and all things web development.

The newsletter is sent every week and includes early access to clear, concise, and easy-to-follow tutorials, and other stuff I think you'd enjoy! No spam ever, unsubscribe at any time.