database 如何在 Sequelize 中使用 findOrCreate
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/43403084/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to use findOrCreate in Sequelize
提问by pekochun
I am a Sequelize beginner. I'd like to oAuth authenticate with Twitter or Facebook and want to save user information in the database.
我是 Sequelize 初学者。我想使用 Twitter 或 Facebook 进行 oAuth 身份验证,并希望将用户信息保存在数据库中。
But if OAuth authentication is done on multiple sites, there is a problem that information such as useridregistered in the database will collide with the other sites.
但是如果在多个站点上进行OAuth认证,存在userid数据库中注册等信息会与其他站点发生冲突的问题。
In order to avoid this, I would like to do a process to update the database only when the specified useriddoes not already exist in the database.
为了避免这种情况,我想做一个过程,仅当指定userid的数据库不存在时才更新数据库。
I knew that we could use Sequelize's findOrCreateto do it, but I do not know how to use findOrCreate.
I know how to use upsert and I'd like to use findOrCreatelike the description of upsert below. However, we want to perform conditional branching like this:
我知道我们可以使用 SequelizefindOrCreate来做到这一点,但我不知道如何使用findOrCreate. 我知道如何使用 upsert,我findOrCreate想像下面的 upsert 描述一样使用。但是,我们希望像这样执行条件分支:
if (userid! = "○○○" && username! = "○○○").
if (userid! = "○○○" && username! = "○○○").
User.upsert({
userid: profile.id,
username: profile.username,
accountid: c + 1,
}).then(() => {
done(null, profile);
});
What should I do?
我该怎么办?
回答by Adhyatmik
// 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
}
});
});
回答by Mark Hymanson
Another option is to use Sequelize hooks. You'd want to make your hook callback async (Sequelize supports it), so in the hook you can run your check and return a promise only if your check is successful (and throw an error otherwise).
另一种选择是使用 Sequelize 钩子。您希望使钩子回调异步(Sequelize 支持它),因此在钩子中您可以运行检查并仅在检查成功时返回承诺(否则抛出错误)。

