加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > MsSql教程 > 正文

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

发布时间:2020-12-12 06:54:08 所属栏目:MsSql教程 来源:网络整理
导读:我是Sequelize初学者. 我想oAuth通过Twitter或Facebook进行身份验证,并希望将用户信息保存在数据库中. 但是,如果在多个站点上进行oAuth身份验证,则存在一个问题,即在数据库中注册的用户ID等信息将与其他站点重复. 为了避免这种情况,我想只在数据库中不存在指
我是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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读