mobizen
mobizen

Reputation: 493

Inserting the records in the table if not exists after sequelize.sync({force:true}) is called

I need to add some records to the table if there is no record exists. For now, I have written the logic to add the records in the callback function of the sequelize.sync({force:true}). I have checked whether the table contains atleast one record, and if not, I have inserted the set of records. Is there any other elegent way to obtain this functionality?

Upvotes: 7

Views: 10998

Answers (2)

Thomas Skubicki
Thomas Skubicki

Reputation: 637

You can use findOrCreate

Like.findOrCreate({
    where: {//object containing fields to found
        InstagramPostId: inputLike.InstagramPostId,
        InstagramUserId: inputLike.InstagramUserId
    },
    defaults: {//object containing fields and values to apply
        postInstagramPostId: inputLike.postInstagramPostId,
        userInstagramUserId: inputLike.userInstagramUserId
    }
}).error(function(err){//error handling
        console.log(err);
}).then(function(){//run your calllback here
    console.log("callback!!");
});

Upvotes: 13

user13423787
user13423787

Reputation:

Updated 02/07/2021: Use this code: Tested! Run ok.

Like.findOrCreate({
        where: {//object containing fields to found
            InstagramPostId: inputLike.InstagramPostId,
            InstagramUserId: inputLike.InstagramUserId
        },
        defaults: {//object containing fields and values to apply
            postInstagramPostId: inputLike.postInstagramPostId,
            userInstagramUserId: inputLike.userInstagramUserId
        }
        }).then(function(){//run your calllback here
          console.log("callback!!");
        }).catch(err => {
          res.status(500).send("Error -> " + err);
        });

Upvotes: -2

Related Questions