如何在 Sequelize 中使用 findOrCreate [英] How to use findOrCreate in Sequelize
问题描述
我是 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认证,存在数据库中注册的userid
等信息会与其他站点发生冲突的问题.
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屋!