猫鼬-如何查询自我参照关系?

时间:2020-02-25 17:14:51

标签: node.js mongodb mongoose mongoose-schema

我想为带有评论的评论实现父/子(自引用)关系,这是该模式的代码:

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

1 个答案:

答案 0 :(得分:1)

我终于设法通过向架构中添加virtual type来获得结果,并使用递归方法来获取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可能有内置的方法或适当的方法来执行此操作。