mongodb - 如何控制 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;
}
我想通过他们的父母评论来获得所有孩子,我花了几个小时,但我不明白任何帮助
解决方案
我尝试通过查找来解决此问题:
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 来保留不包含孩子的父母。但是我得到的是新的组合+没有孩子的父母+孩子。我想删除孩子,任何想法
推荐阅读
- python - 如何在python中遍历重复并创建映射
- ag-grid-angular - 使用全行编辑时如何检测 AgGrid 中的单个单元格变化?
- python - 如何在水平栏中显示数据的频率?
- java - 如何在 Windows 10 中为 Java 中的方法 SerialPort.getCommPort() 获取串行端口的名称
- ember.js - 如何在 ember js 中一次只打开一个菜单项?
- api - 如何在 Airflow DAG 上自动获取 API 令牌
- bash - bash 可以检索脚本中的整个命令吗?
- javascript - 为什么我需要这个。关键字引用同名变量?
- python - 解码 Decimal 类型的 parquet 最小/最大统计信息
- javascript - Vue 3, call $emit on variable change