gpt4 book ai didi

node.js - Mongoose - 如何查询自引用关系?

转载 作者:太空宇宙 更新时间:2023-11-03 23:47:50 26 4
gpt4 key购买 nike

我想为评论及其回复实现父/子(自引用)关系,以下是架构代码:

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,评论 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

最佳答案

我终于通过添加 virtual type 得到了结果。到我的架构并使用递归方法来获取回复总数:

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 来做到这一点。

关于node.js - Mongoose - 如何查询自引用关系?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60399976/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com