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?
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.
upsert() returns a boolean indicating whether the row was created or updated.
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.
// 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
}
});
});
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With