Find one or create with Mongoose : <p>I have </p>

<pre><code>Page.findById(pageId).then(page =&gt; {
  const pageId = page.id;
   ..
});
</code></pre>

<p>My problem is that if no page id is given, it should just take the first available page given some conditions, which is done by</p>

<pre><code>Page.findOne({}).then(page =&gt; {
  const pageId = page.id;
  ..
});
</code></pre>

<p>but if no page is found, it should create a new page and use this, which is done with</p>

<pre><code>Page.create({}).then(page =&gt; {
  const pageId = page.id;
  ..
});
</code></pre>

<p>But how do I combine all this to as few lines as possible?</p>

<p>I have a lot of logic going on inside</p>

<pre><code>page =&gt; { ... }
</code></pre>

<p>so I would very much like to do this smart, so I can avoid doing it like this</p>

<pre><code>if (pageId) {
  Page.findById(pageId).then(page =&gt; {
    const pageId = page.id;
     ..
  });
} else {
  Page.findOne({}).then(page =&gt; {
    if (page) {
      const pageId = page.id;
      ..
    } else {
      Page.create({}).then(page =&gt; {
        const pageId = page.id;
        ..
      });
    }
  });
}
</code></pre>

<p>I am thinking I maybe could assign a static to the schema with something like</p>

<pre><code>pageSchema.statics.findOneOrCreate = function (condition, doc, callback) {
  const self = this;
  self.findOne(condition).then(callback).catch((err, result) =&gt; {
    self.create(doc).then(callback);
  });
};
</code></pre>
