How to use findOrCreate in Sequelize

I'm starting to start. I would like to authenticate using Twitter or Facebook and save the user information in the database. But if oAuth authentication is performed on several sites, there is a problem that information, such as the user ID registered in the database, will be duplicated with another site. To avoid this, I would like to make the database update process only when the specified user ID does not already exist in the database. I knew that we could use exelize findOrCreate for such processing, but I do not know how to use findOrCreate. I know how to use upsert, and I would like to find findOrCreate, as the description of upsert is below. However, we want to do conditional branching, for example if (userid! = "○○○" & username! = "○○○").

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

What should I do?

+8
source share
2 answers
// 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
    }
  });
});

+11
source

Another option is to use Sequelize hooks. You would like to make your interception callback asynchronous (Sequelize supports it), so in interception mode you can only perform your verification and return a promise if your verification is successful (and otherwise generates an error).

0
source

Source: https://habr.com/ru/post/1674790/


All Articles