Skip to content Skip to sidebar Skip to footer

Find One Or Create With Mongoose

I have Page.findById(pageId).then(page => { const pageId = page.id; .. }); My problem is that if no page id is given, it should just take the first available page given s

Solution 1:

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)

Solution 2:

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

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

And then use it like:

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

Solution 3:

Promise async/await version.

Page.static('findOneOrCreate', async function findOneOrCreate(condition, doc) {
  const one = awaitthis.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);
}

Solution 4:

Each Schema can define instance and static methods for its model. Statics are pretty much the same as methods but allow for defining functions that exist directly on your Model

Static method findOneOrCreate:

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

Now when you have an instance of Page you can call findOneOrCreate:

Page.findOneOrCreate({id: 'somePageId'}, (err, page) => {
  console.log(page);
});

Solution 5:

One lines solution with async/await:

const page = Page.findOne({}).then(p => p || p.create({})

Post a Comment for "Find One Or Create With Mongoose"