Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Web Technology by (50.2k points)

I have

Page.findById(pageId).then(page => {

  const pageId = page.id;

   ..

});

My query is that if no page id is provided, it should just use the first available page provided some conditions, which is done by

Page.findOne({}).then(page => {

  const pageId = page.id;

  ..

});

but if there is no page then it should create a new page and use this, which is done with

Page.create({}).then(page => {

  const pageId = page.id;

  ..

});

But all I want is to merge all this to a few lines... Is it possible?

1 Answer

0 votes
by (107k points)

What you can do is use the function findOneOrCreate() in MongoDB, just refer te following code:

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 after that, you can use it like the following:

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

    // ... code

    console.log(page)

})

Related questions

0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
asked Feb 16, 2020 in Web Technology by ashely (50.2k points)

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...