How to use findOrCreate in Sequelize
// 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).