21

I am a 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 collide with the other sites.

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

What should I do?

3 Answers 3

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

1
  • 5
    Worth noting that Sequelize will automatically create the transaction if one is not provided in the options to findOrCreate
    – agmin
    Jan 16, 2020 at 15:37
3

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

1

In findOrCreate() method defaults: option is significant and valuable.

You can use some values for where: condition and add the remaining in defaults: option.

User.findOrCreate({
   where: {userId: profile.id},
   defaults: {
        name: profile.name,
        address: profile.address,
   }
}).then((userRow, isCreated) => {
if(isCreated){
       //user created
       console.log('creted user', userRow);
   }
});

In the above example, we're not adding name and address values in the where: condition because I believe name and address can be the same and these are also not unique in the table.

1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.