Hel*_*815 8 javascript mysql orm node.js sequelize.js
我的应用程序有很多用户可以喜欢很多帖子(N到N).这就是我为我的模型(Sequelize Doc)分配以下"belongsToMany"关系的原因:
// Post Model
models.Post.belongsToMany(models.User, { through: models.PostLikes});
// User Model
models.User.belongsToMany(models.Post, { through: models.PostLikes});
Run Code Online (Sandbox Code Playgroud)
在我的Post Controller中,我得到了"likePost"函数的以下用例:
如果不是,则在User和Post之间分配N到N的关系.(似乎工作)
// 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);
};
Run Code Online (Sandbox Code Playgroud)现在我遇到了问题,我无法检查用户是否已经喜欢帖子."req.user.hasPost(postToLike).isFulfilled()"总是返回false,即使我确实可以在我的"PostLikes"数据库表中看到正确的关系.那我怎么能正确地说:
BTW这就是我的PostLikes Table的样子:
+----+--------+--------+
| id | userId | postId |
+----+--------+--------+
| 1 | 2 | 3 |
+----+--------+--------+
Run Code Online (Sandbox Code Playgroud)