How to use findOrCreate in Sequelize

本小妞迷上赌 提交于 2020-01-12 03:21:28

问题


I am Sequelize beginner. I'd like to oAuth authenticate with Twitter or Facebook and want to save user information in the database. But if oAuth authentication is done on multiple sites, there is a problem that information such as userid registered in the database will duplicate with other site . 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. I knew that we could use sequelize's findOrCreate to do such processing, but I do not know how to use findOrCreate. I know how to use upsert and I'd like to do findOrCreate like the description of upsert below. However, we want to perform conditional branching like if (userid! = "○○○" && username! = "○○○").

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

What shoudl I do?


回答1:


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




回答2:


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).



来源:https://stackoverflow.com/questions/43403084/how-to-use-findorcreate-in-sequelize

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!