提问者:小点点

如何计算与父模式不同的mongodb模式?


现在我有点小问题。我有一个模式,存储我博客文章。在另一个模式中,我保存注释。在这个模式中,我保存了博客文章中的parent.id。

现在,我要统计评论,在博文下面显示这个计数。(信息:我使用express,Edge.All thinks非常好用!)

我的模块看起来像:

const Post = require('../database/models/Post');
const Comment = require('../database/models/Comment');


module.exports = async(req, res) => {
  const posts = await Post.find({}).sort({ _id: -1 });
  const estimate = await Post.count({}); //all post blogs  
  const comments = await Comment.count({}); //all comments

// here I want to count all comments from one post blog ... etc ...

res.render("index", {
    posts, estimate, comments
  });
}

以下是模式:


const mongoose = require('mongoose');
 
const PostSchema = new mongoose.Schema({
    title: String,
    description: String,
    content: String,
    username: String,
    createdAt: {
        type: Date,
        default: new Date()
    }
});
 
const Post = mongoose.model('Post', PostSchema);
 
module.exports = Post;

--------

const mongoose = require('mongoose');
 
const CommentSchema = new mongoose.Schema({
    comment: {
        type: String,
        //required: true
    },
    username: {
        type: String,
    },
    parent_id: {        // <-- the _id from posts
        type: String
    }
});

var Comment = mongoose.model('Comment', CommentSchema);
module.exports = Comment;

希望有人能给我点提示。

谢谢


共1个答案

匿名用户

我不确定你是想要一个特定帖子的评论计数还是所有帖子的评论计数,所以让我们回顾一下每一个案例。

只需在count函数内部添加一个指定blog ID的查询,就可以做到这一点。

const commentCount = await Post.count({ parent_id: blog_id });

这个要复杂一点。您将需要使用Mongo聚合(您可以在这里阅读有关它们的更多信息)。基本上,您希望按parent_id注释进行分组并对其进行计数,因此如下所示:

const allPostCommentCount = await Comment.aggregate({
  $group: {
    _id: "$parent_id",
    count: {
      $sum: 1,
    },
  },
});