Find one or create with Mongoose Find one or create with Mongoose mongodb mongodb

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)


Related to Yosvel Quintero's answer which didn't work for me:

pageSchema.statics.findOneOrCreate = function findOneOrCreate(condition, callback) {    const self = this    self.findOne(condition, (err, result) => {        return result ? callback(err, result) : self.create(condition, (err, result) => { return callback(err, result) })    })}

And then use it like:

Page.findOneOrCreate({ key: 'value' }, (err, page) => {    // ... code    console.log(page)})


Promise async/await version.

Page.static('findOneOrCreate', async function findOneOrCreate(condition, doc) {  const one = await this.findOne(condition);  return one || this.create(doc);});

Usage

Page.findOneOrCreate({ id: page.id }, page).then(...).catch(...)

Or

async () => {  const yourPage = await Page.findOneOrCreate({  id: page.id }, page);}