调用 sequelize.sync({force:true}) 后如果不存在则插入表中的记录

mob*_*zen 3 node.js sequelize.js

如果没有记录存在,我需要向表中添加一些记录。现在,我已经编写了在 sequelize.sync({force:true}) 的回调函数中添加记录的逻辑。我已经检查了该表是否包含至少一条记录,如果没有,我已经插入了一组记录。有没有其他优雅的方式来获得这个功能?

小智 5

我很晚才回答这个问题,但您可以使用 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!!");
});
Run Code Online (Sandbox Code Playgroud)