如何在Sequelize

时间:2017-04-13 23:15:46

标签: 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);
        });

我做了什么?

2 个答案:

答案 0 :(得分:11)

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

答案 1 :(得分:0)

另一个选择是使用Sequelize挂钩。您希望使钩子回调异步(Sequelize支持),因此在钩子中,您可以运行检查并仅在检查成功时返回承诺(否则抛出错误)。