微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

数据库 – 如何在Sequelize中使用findOrCreate

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

我在做什么?

解决方法

// remember to use transaction as you are not sure
// whether 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:    profiile.userId,name:      profiile.name
    },transaction: t
  })
  // necessary to use spread to find out if user was found or created
  .spread(function(userResult,created){
    // this userId was either created or found depending upon whether the argment 'created' is true or false
    // do something with this user Now
    if (created){
      // some logic
    }
    else {
      // some other logic
    }     
  }); // end spread
}) // end transaction

原文地址:https://www.jb51.cc/mssql/77602.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐