Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use findOrCreate in Sequelize

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?

like image 876
pekochun Avatar asked Apr 13 '17 23:04

pekochun


People also ask

How do I use Groupby Sequelize?

In Sequelize, you can add the group option in your query method findAll() to add the GROUP BY clause to the generated SQL query. Now you want to select all firstName values and group any duplicate values of the column. Here's the code for calling the findAll() method on the model: const users = await User.

What is Upsert Sequelize?

upsert() returns a boolean indicating whether the row was created or updated.

What is raw true in Sequelize?

According to the doc : If you do not provide other arguments than the SQL, raw will be assumed to the true, and sequelize will not try to do any formatting to the results of the query.


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

like image 94
Adhyatmik Avatar answered Oct 24 '22 22:10

Adhyatmik


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

like image 3
Mark Jackson Avatar answered Oct 24 '22 22:10

Mark Jackson