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

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

问题描述

我有

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的答案有关:

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天全站免登陆