Sequelize:检查并添加BelongsToMany(N到N)关系

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"函数的以下用例:

  1. 检查帖子是否存在.(似乎工作)
  2. 如果是,请检查用户是否已经喜欢此帖子.
  3. 如果不是,则在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"数据库表中看到正确的关系.那我怎么能正确地说:

  1. 检查用户是否已经喜欢帖子.
  2. 分配这种关系.
  3. 并删除与Sequelize的关系?

BTW这就是我的PostLikes Table的样子:

+----+--------+--------+
| id | userId | postId |
+----+--------+--------+
|  1 |      2 |      3 |
+----+--------+--------+
Run Code Online (Sandbox Code Playgroud)

che*_*ish 1

查看文档,没有提及isFulfilled()。你尝试去做了吗req.user.hasPost(postToLike)?(续集文档

  • isFullfilled() 一般不直接访问。**await** 期望一个承诺,并且通过调用 isFullfilled(),它没有得到等待的承诺。如果解决了问题,请采纳答案,谢谢:) (2认同)