如何计算不同于父模式的mongodb模式



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

现在,我想统计一下评论,在博客下面显示这个计数。(信息:我用快递,边缘。所有人都认为效果很好!(

我的模块看起来像:

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;

希望有人能给我一个提示。

感谢

----------------------8&lt------------8&lt-------------------编辑:

我的index.edge:

@each(post in posts)
<!-- some code here -->
{{ post._id }}   <-- current post id
@if(post._id == allPostCommentCounts._id)
have comments
@else
no comments
@endif
tried:
@if(allPostCommentCounts.count > 0)
have posts {{ allPostCommentCounts.count }}
@endif
@endeach

if语句不起作用。

console.log来自所有PostCommentCount和posts:

[
{ _id: '5f96c97a8cad2c5250597b0b', count: 2 },
{ _id: '5f9ee8fcfc7fb52de8c9ab50', count: 3 }
]
[
{
createdAt: 2020-11-01T16:55:49.139Z,
_id: 5f9ee8fcfc7fb52de8c9ab50,
username: 'f',
title: 'f',
description: '',
content: 'fff',
__v: 0
},
...
}
]

嗯。。。我不知道怎么了。

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

一篇文章的评论数

这可以通过简单地在count函数中添加一个查询来完成,该函数指定博客id。

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

所有帖子的评论计数

这个有点复杂。您将需要使用Mongo聚合(您可以在这里阅读更多关于它们的信息(。基本上,你想用parent_id对你的Comments进行分组并计数,所以它应该是这样的:

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

最新更新