【问题标题】:How to use findOrCreate in Sequelize如何在 Sequelize 中使用 findOrCreate
【发布时间】:2020-01-31 14:15:34
【问题描述】:

我是 Sequelize 初学者。 我想通过 Twitter 或 Facebook 进行 oAuth 身份验证,并希望将用户信息保存在数据库中。

但是如果在多个站点上进行OAuth认证,就会出现在数据库中注册的userid等信息会与其他站点发生冲突的问题。

为了避免这种情况,我想只在指定的userid在数据库中不存在时才更新数据库。

我知道我们可以使用 Sequelize 的findOrCreate 来做到这一点,但我不知道如何使用findOrCreate。 我知道如何使用 upsert,我想使用 findOrCreate,就像下面对 upsert 的描述一样。但是,我们希望像这样执行条件分支:

if (userid! = "○○○" && username! = "○○○").

User.upsert({
  userid:    profile.id,
  username:  profile.username,
  accountid: c + 1,
}).then(() => {
  done(null, profile);
});

我该怎么办?

【问题讨论】:

    标签: database oauth sequelize.js


    【解决方案1】:
    // remember to use a transaction as you are not sure whether the user is
    // already present in DB or not (and you might end up creating the user -
    // a write operation on DB)
    
    models.sequelize.transaction(function(t) {
      return models.users.findOrCreate({
        where: {
          userId:    profile.userId,
          name:      profile.name
        },
        transaction: t
      })
      .spread(function(userResult, created){
        // userResult is the user instance
    
        if (created) {
          // created will be true if a new user was created
        }
      });
    });
    
    

    【讨论】:

    • 值得注意的是,如果findOrCreate的选项中没有提供,Sequelize 会自动创建交易
    【解决方案2】:

    另一种选择是使用 Sequelize 挂钩。你想让你的钩子回调异步(Sequelize 支持它),所以在钩子中你可以运行你的检查并只有在你的检查成功时才返回一个承诺(否则抛出一个错误)。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-04-12
      • 2017-03-16
      • 1970-01-01
      • 2020-12-01
      • 2018-04-05
      • 2014-01-05
      • 1970-01-01
      • 2020-11-10
      相关资源
      最近更新 更多