如何在Sequelize中使用findOrCreate

pek*_*hun 9 database oauth sequelize.js

我是Sequelize初学者.我想oAuth通过Twitter或Facebook进行身份验证,并希望将用户信息保存在数据库中.但是,如果在多个站点上进行oAuth身份验证,则存在一个问题,即在数据库中注册的用户ID等信息将与其他站点重复.为了避免这种情况,我想只在数据库中尚不存在指定的用户标识时才进行更新数据库的过程.我知道我们可以使用sequelize的findOrCreate来进行这样的处理,但我不知道如何使用findOrCreate.我知道如何使用upsert,我想做findOrCreate,如下面的upsert描述.但是,我们想要执行条件分支,如if(userid!="○○○"&& username!="○○○").

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

我在做什么?

Adh*_*mik 12

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

Run Code Online (Sandbox Code Playgroud)

  • 值得注意的是,如果 [findOrCreate](https://sequelize.org/master/class/lib/model.js~Model.html#static-method-findOrCreate) 选项中未提供交易,Sequelize 将自动创建交易 (5认同)