如何在Sequelize中使用findOrCreate [英] How to use findOrCreate in Sequelize

查看:1967
本文介绍了如何在Sequelize中使用findOrCreate的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Sequelize初学者。
我想通过Twitter或Facebook进行oAuth身份验证,并希望将用户信息保存在数据库中。

I am a Sequelize beginner. I'd like to oAuth authenticate with Twitter or Facebook and want to save user information in the database.

但是如果OAuth身份验证是在多个站点上进行的,存在一个问题,例如在数据库中注册的用户ID 之类的信息将与其他站点冲突。

But if OAuth authentication is done on multiple sites, there is a problem that information such as userid registered in the database will collide with the other sites.

为避免这种情况,我只想在数据库中不存在指定的 userid 时执行更新数据库的过程。

In order to avoid this, I would like to do a process to update the database only when the specified userid does not already exist in the database.

我知道我们可以使用Sequelize的 findOrCreate 来做,但是我不知道如何使用 findOrCreate
我知道如何使用upsert,我想使用 findOrCreate 像下面对upsert的描述。但是,我们希望执行如下条件分支:

I knew that we could use Sequelize's findOrCreate to do it, but I do not know how to use findOrCreate. I know how to use upsert and I'd like to use findOrCreate like the description of upsert below. However, we want to perform conditional branching like this:

if(userid!=○○○&& username!= ○○○)

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

我该怎么办?

推荐答案

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

这篇关于如何在Sequelize中使用findOrCreate的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆