【问题标题】:(Mongoose) How to have bi-directional reference between Post and Comment model(Mongoose) 如何在 Post 和 Comment 模型之间进行双向引用
【发布时间】:2020-11-15 13:36:38
【问题描述】:

所以,我有一个(猫鼬)帖子模型和评论模型,我想在不存储整个子文档的情况下链接这两者,我的要求是在帖子中存在对子评论的引用数组和一个评论以具有对其父帖子的单一引用。 编辑:是否可以自动设置参考?

【问题讨论】:

    标签: javascript node.js database mongodb mongoose


    【解决方案1】:

    您必须使用mongoose.Schema.Types.ObjectId 类型才能引用另一个集合。它的作用类似于 SQL 语言中的 foreignKey。

    但你第二个问题的答案是否定的。你必须手动设置。

    顺便说一句,更好的设计是将您的引用或 foreignKey 存储在两个集合之一中,而不是两个集合中。

    在数据库语言中,如果您有one-to-many 关系,就像这里您的帖子有很多 cmets,更好的方法是将 postId(作为 foreignKey)存储在评论集合中。当您想要查找特定帖子的所有 cmets 时,您可以查询您的 cmets 集合并仅查找具有您特定 postId 的记录。

    这是评论模式:

    let commentSchema = new mongoose.Schema({
      text: String,
      post: {
        type: mongoose.Schema.Types.ObjectId,
        ref: 'Post'
      }
    });
    

    这是帖子架构

    let postSchema = new mongoose.Schema({
      text: String,
      comments: [{
        type: mongoose.Schema.Types.ObjectId,
        ref: 'Comment',
        default: []
      }]
    });
    

    这里是创建帖子和 cmets 的代码:

    const createPost = async () => {
     let post = new PostModel({
       text: 'Here is a sample post',
     });
     await post.save();
    }
    
    const createCommentOnPost = async (postId) => {
      let comment = new Comment({
        text: 'Sample comment',
        post: postId
      });
      await comment.save();
      await Post.updateOne({_id: postId}, {$push: {comments: comment}});
    }
    

    【讨论】:

    • 我在每篇文章中都使用了对作者的 ObjectId 引用,但我真的不知道如何以这种方式实现它,所以谢谢你,而且我认为路由无论如何都会包含帖子的 ID 所以手动操作不会太难。
    猜你喜欢
    • 2012-02-01
    • 2012-05-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-04
    • 2013-04-13
    • 2013-04-05
    相关资源
    最近更新 更多