首页 > 解决方案 > MongoDB/Mongoose:如何计算一个集合中的文档并根据 id 将其添加到另一个集合中?

问题描述

你好美丽的社区。希望你们一切都好。

所以我正在开发这个应用程序,我有两个 MongoDB 集合,Posts并且CommentsView.

Posts集合由post titlepost type它们组成comments。这comments是一个对象数组,由每个评论被查看的次数和 id 组成。

CommentsView集合中,我打算在查看时存储所有评论。重复不是问题。

架构如下所示:

帖子架构:

const postsSchema = new mongoose.Schema( {
    postTitle: {
        type: String
    },
    comments: [ {
        totalViews: {
            type: Number
        },
        uid: {
            type: String
        }
    }],
    postId: {
        type: String
    }
} );

评论视图架构:

const commentsViewSchema = new mongoose.Schema( {
    text: {
        type: String,
    },
    uid: {
        type: String
    }
} );

假设我的帖子有两条评论,分别带有 uid 'A' 和 'B'。每当查看带有 uid 'A' 的评论时,我都会在CommentsView集合中创建一个评论。并自动在Posts集合的totalView字段中添加 1 个视图。当再次查看相同的评论时,我将首先将其添加到集合中,然后在帖子集合中CommentsView增加字段。totalView

假设我在 Comments 集合中有这些文档:

{
    text: 'Life is good',
    uid: 'A'
},
{
    text: 'Boom Boom',
    uid: 'B'
},
{
    text: 'Bam Bam',
    uid: 'A'
},

所以 Posts 文档将如下所示:

{
    postTile: '60 seconds to Mars',
    comments: [
        {
             uid: 'A',
             totalViews: 2,
        },
        {
             uid: 'B',
             totalViews: 1,
        },
    ],
    postId: '1s93njs'    
}

我还没有尝试过任何东西,因为我不知道从哪里开始。看起来好复杂。

如果我希望整个过程是自动的,我该如何实现?

标签: node.jsmongodbexpressmongoose

解决方案


由于您使用的是两种不同的模式,我建议您使用引用,因为如果您想添加更多功能,例如点赞数和线程数,那么下面建议的这个模型将很有用

不要使用String类型来存储模型的 Id,使用 mongoose 模块提供的类型ObjectId

后模型

const postsSchema = new mongoose.Schema( {
postTitle: {
    type: String
},
comments: [ 
    type:ObjectId,
    ref:"model name"
],
    postId: {
      type: String
    }
}, {timestamps:true});

评论模型

 const commentsViewSchema = new mongoose.Schema( {
       text: {
         type: String,
         required:true
       },
       totalView:{
          type: Number,
          default:0
       }
  },{timestamps:true} );

现在每次查看帖子时,您都可以搜索评论 ID 并增加文档中的计数。如果您填充数组中的所有评论,所有内容都将反映在帖子模型中

例子

工作流程

用户查看了评论-->(getcomment_id) --> 更新评论

现在,由于引用,所有后续对带有此评论的帖子的请求也将具有更新的视图。

查询以更新评论

comment.findByIdAndUpdate({_id:<comment_id>}, {$inc:{totalView:1}})

另一种方法是嵌入do,如果您认为帖子不会有太多评论,我建议您这样做,否则有上述模型很好。

您可以进一步参考这些文章

设计 mongodb 模式要遵循的规则

希望这可以帮助您获得一个好主意


推荐阅读