Find one or create with Mongoose

As per the Mongoose docs:

As per previous SO answer

Model.findByIdAndUpdate()

“Finds a matching document, updates it according to the update arg, passing any options, and returns the found document (if any) to the callback.”

In the options set upsert to true:

upsert: bool – creates the object if it doesn’t exist. defaults to false.

Model.findByIdAndUpdate(id, { $set: { name: 'SOME_VALUE' }}, { upsert: true  }, callback)

Leave a Comment