查找或使用猫鼬创建 [英] Find one or create with Mongoose

查看:34
本文介绍了查找或使用猫鼬创建的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有

Page.findById(pageId).then(page => {
  const pageId = page.id;
   ..
});

我的问题是,如果没有给出页面 id,它应该只在给定一些条件的情况下取第一个可用页面,这是由

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

Page.findOne({}).then(page => {
  const pageId = page.id;
  ..
});

但是如果没有找到页面,它应该创建一个新页面并使用它,这是用

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

Page.create({}).then(page => {
  const pageId = page.id;
  ..
});

但是我如何将所有这些组合成尽可能少的行?

But how do I combine all this to as few lines as possible?

我有很多逻辑在里面

page => { ... }

所以我很想聪明地做这个,所以我可以避免这样做

so I would very much like to do this smart, so I can avoid doing it like this

if (pageId) {
  Page.findById(pageId).then(page => {
    const pageId = page.id;
     ..
  });
} else {
  Page.findOne({}).then(page => {
    if (page) {
      const pageId = page.id;
      ..
    } else {
      Page.create({}).then(page => {
        const pageId = page.id;
        ..
      });
    }
  });
}

我想我也许可以用类似的东西为架构分配一个静态

I am thinking I maybe could assign a static to the schema with something like

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

推荐答案

Yosvel Quintero 的 答案有关,但对我不起作用:

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) })
    })
}

然后像这样使用它:

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

这篇关于查找或使用猫鼬创建的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆