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

西尔万·阿菲菲

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

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可能有内置的方法或适当的方法来执行此操作。

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章