My application got many Users who can like many Posts (N to N). That's why I assigned the following "belongsToMany" Relations for my Models (Sequelize Doc):
// Post Model
models.Post.belongsToMany(models.User, { through: models.PostLikes});
// User Model
models.User.belongsToMany(models.Post, { through: models.PostLikes});
Inside my Post Controller I got the following use case for the "likePost" function:
If not, assign the N to N relation between User and the Post. (seems to work)
// User likes Post
exports.likePost = async (req, res) => {
const postToLike = await Post.findById(req.body.postId);
// Check if the Post exists
if (!postToLike) {
return res.status(404).json({ error: { message: 'Post not found.' }});
}
// Did user already like the post?
// HERE IS THE NOT WORKING PART:
if (await req.user.hasPost(postToLike).isFulfilled()) {
return res.status(422).json({ error: { message: 'Already liked post.' }});
}
// add Like
await req.user.addPost(postToLike);
return res.send(postToLike);
};
Now I got the Problem, that I am not able to check if a User already liked a Post. "req.user.hasPost(postToLike).isFulfilled()" always returns false, even if indeed I can see the correct relation in my "PostLikes" DB Table. So how can I correctly:
BTW this is how my PostLikes Table looks like:
+----+--------+--------+
| id | userId | postId |
+----+--------+--------+
| 1 | 2 | 3 |
+----+--------+--------+
You need to call the belongsToMany() method and pass the junction table using the through option as shown below: Student. belongsToMany(Class, { through: Enrollment }); Class. belongsToMany(Student, { through: Enrollment });
Looking at the documentation, there is no mention of isFulfilled().
Did you try to do req.user.hasPost(postToLike)
?
(Sequelize Doc)
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