Ryan
Ryan

Reputation: 151

How do I create a method on a sequelize object that checks if there is an another object created that is associated with it?

Sorry, my title is probably confusing.

So I have three objects I created with sequelize in javascript. User, Post, and Vote that are all associated with one another. I want to create a method on the Post model to check if the current signed in User has voted on this particular post. I am using the Passport module for user sign in/sign out.

Upvotes: 0

Views: 33

Answers (1)

Vivek Doshi
Vivek Doshi

Reputation: 58573

var Votes = db.sequelize.define('votes',{
    post_id:{
        type: db.Sequelize.INTEGER,
        allowNull: false,
        unique:"voted_user"
    },
    user_id:{
        type: db.Sequelize.INTEGER,
        allowNull: false,
        unique:"voted_user"
    }
},{
    underscored: true
});

For that you can use the concept of the composite key , by defining the unique:"voted_user" , This will throw error when we try to enter same combination ,

model.Votes.create({ post_id : 1 , user_id : 2 }).then(data => {
    // Success
}).catch(err => {
    // Error
})

Upvotes: 1

Related Questions