如何在Sequelize中使用findOrCreate

问题描述 投票:8回答:2

我是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);
        });

我该怎么办?

database oauth sequelize.js
2个回答
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
    }
  });
});


0
投票

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

© www.soinside.com 2019 - 2024. All rights reserved.