首页 > 解决方案 > 如何控制 find() 以获取所有具有父注释的子项

问题描述

我是 mongoose 的大佬,我实现了评论的概念。事实上,我创建了一个模式注释,我在其中标识了不同的字段,如下所示:

import mongoose from 'mongoose';
/* eslint-disable-next-line */
import db from './db';

// Define Schema method= mongoose;
const { Schema } = mongoose;
const CommentSchema = new Schema({
  id: {
    type: String,
    required: true,
    unique: true,
  },
  author_id: {
    type: String,
    required: true,
  },
  content: {
    type: String,
  },
  creation_date: {
    type: Date,
    default: Date.now,
  },
  interesting_comment: [String],
  updated_content_list: [{ previous_date: Date, previous_content: String }],
  children: [String],
});
export default mongoose.model('Comment', CommentSchema);

注意:children 是关于对父母评论的回应,这里是例子:

{
    "_id" : ObjectId("60217951f57f24079f885d66"),
    "interesting_comment" : [
        "6ff10e9"
    ],
    "children" : [
        "c13e5487-07ba-4bc9-996e-ef1c8f826b32"
    ],
    "updated_content_list" : [ ],
    "id" : "6f169ee4-d22d-49a2-9f71-5dacadecf6bb",
    "author_id" : "b08a3310-b3f4-4521-9b1a-2d5667a3ea1d",
    "content" : "Hello wijdene",
    "creation_date" : ISODate("2021-02-08T17:48:01.026Z"),
    "__v" : 4
}
{
    "_id" : ObjectId("602179d1f57f24079f885d68"),
    "interesting_comment" : [ ],
    "children" : [ ],
    "updated_content_list" : [ ],
    "id" : "c13e5487-07ba-4bc9-996e-ef1c8f826b32",
    "author_id" : "111",
    "content" : "hi nesrine",
    "creation_date" : ISODate("2021-02-08T17:50:09.075Z"),
    "__v" : 0
}

我实现了这个功能:

async function ListComment() {
  const comments = await Comment.find();
  return comments;
}

我想通过他们的父母评论来获得所有孩子,我花了几个小时,但我不明白任何帮助

标签: mongodbmongoosemongoose-schema

解决方案


我尝试通过查找来解决此问题:

async function ListComment() {
  const comments = await Comment.aggregate([{$unwind:{path:"$children",preserveNullAndEmptyArrays: true}},{$lookup:{from:"comments",localField:"children",foreignField:"id",as:"children"}}]);
  return comments;
}

但即使是孩子,也是这样表现出来的。事实上,我添加了 preserveNullAndEmptyArrays: true 来保留不包含孩子的父母。但是我得到的是新的组合+没有孩子的父母+孩子。我想删除孩子,任何想法


推荐阅读