Mongoose-如何查询自引用关系



我想实现注释及其回复的父/子(自引用(关系,下面是架构的代码:

const mongoose = require("mongoose");
const Schema = mongoose.Schema;
const BlogCommentSchema = new Schema({
body: String,
dateTime: { type: Date, default: Date.now },
replies: [this]
});
const BlogComment = mongoose.model("blogComments", BlogCommentSchema);
module.exports = BlogComment;

获取评论或回复数量的最简单方法是什么?

如有任何帮助,我们将不胜感激。

澄清:下面是一个基于模式保存文档的示例:

{
"replies": [
{
"replies": [
{
"replies": [],
"_id": "5e558aa01f804205102b4a78",
"body": "Comment 1.1.1",
"dateTime": "2020-02-25T20:59:12.056Z"
}
],
"_id": "5e558aa01f804205102b4a79",
"body": "Comment 1.1",
"dateTime": "2020-02-25T20:59:12.057Z"
},
{
"replies": [
{
"replies": [
{
"replies": [
{
"replies": [
{
"replies": [],
"_id": "5e558aa01f804205102b4a7a",
"body": "Comment 1.2.1.1.1",
"dateTime": "2020-02-25T20:59:12.057Z"
}
],
"_id": "5e558aa01f804205102b4a7b",
"body": "Comment 1.2.1.1.1",
"dateTime": "2020-02-25T20:59:12.057Z"
}
],
"_id": "5e558aa01f804205102b4a7c",
"body": "Comment 1.2.1.1",
"dateTime": "2020-02-25T20:59:12.057Z"
}
],
"_id": "5e558aa01f804205102b4a7d",
"body": "Comment 1.2.1",
"dateTime": "2020-02-25T20:59:12.058Z"
}
],
"_id": "5e558aa01f804205102b4a7e",
"body": "Comment 1.2",
"dateTime": "2020-02-25T20:59:12.058Z"
}
],
"_id": "5e558aa01f804205102b4a7f",
"body": "Comment 1",
"dateTime": "2020-02-25T20:59:12.058Z",
"__v": 0
}

我需要得到这些数字(回复总数是7,Comment 1.1的数量是1,…(:

Comment 1 (count is 7)
- Comment 1.1 (count 1)
- Comment 1.1.1
- Comment 1.2 (count 4)
- Comment 1.2.1
- Comment 1.2.1.1
- Comment 1.2.1.1.1
- Comment 1.2.1.1.1.1

我最终设法通过向我的模式中添加一个虚拟类型来获得结果,并使用递归方法来获得replies:的总数

const getRepliesCount = (comment, count = 0) => {
if (comment.replies.length === 0) {
return 1;
}
for (const reply of comment.replies) {
count += getRepliesCount(reply, count);
}
return count;
};

BlogCommentSchema.virtual("total").get(function() {
return getRepliesCount(this) + 1;
});

尽管我希望有一种内置的方法或使用MongoDB/Mongoose的正确方法来实现这一点。

最新更新