Support Ukraine 🇺🇦Help Ukrainian ArmyHumanitarian Assistance to Ukrainians

How to create a document only if it doesn't exist already using Mongoose?


Jan 06 2020 at 09:08 GMT

I want to query a Topic given its name, and create one if it doesn't exist already.

How to do that in Mongoose?

1 Answer


Jan 06 2020 at 09:13 GMT

You can use Model.findOneAndModify():

const dancingTopic = await Topic.findOneAndModify(
  { name: 'Dancing' },
  { upsert: true, new: true }

This will either return the existing topic if it already exists or create a new topic with name: 'Dancing' if it doesn't and return it.

The second argument, {}, is the update object with the fields to update for the existing/new document. Here we just pass an ampty object, but if there is a field you want to update, you can specify it there.

The upsert: true option makes sure that a new document is created if one doesn't exist.

The new: true option makes sure that you get the newly created object or the updated object. If this is not set, you get null if the object didn't exist and was created, or the version before the update was applied if the object existed and was updated.

claritician © 2022