node.js - mongoose - 我想查找包含嵌套引用的文档?
问题描述
我是 mongoose 和 MongoDB 的新手,我有一个问题,我想查找包含参考参考的文档。
我有2个这样的模型:
1:带有参考类别的帖子:
const postsSchema = new Schema({
post_title: {
type: String,
required:true
},
post_categories: [{
type: Schema.Types.ObjectId,
ref: 'categories',
required:true
}],
});
2: 引用类别的类别
const categoriesSchema = new Schema({
categoryName: {
type: String,
required: true
},
categoryParent: {
type: Schema.Types.ObjectId,
ref: 'categoriesSchema',
}
});
我想查找所有具有父类别的帖子,例如(新闻),我试试这个:
Posts.find({'post_categories.categoryParent.categoryName': 'news'});
但我有一个空数组[]。有没有办法找到包含参考参考的文件?
解决方案
我通过使用 MongoDB 聚合找到了解决方案,我不知道它是否是最佳解决方案,但它解决了我的问题:
var allnews = await postsDB.aggregate([
{$unwind: "$post_categories"},
{$lookup: {
from: "categories",
localField: "post_categories",
foreignField: "_id",
as: "newCategoryName"
}},
{ $unwind: "$newCategoryName"
},
{$lookup: {
from: "categories",
localField: "newCategoryName.categoryParent",
foreignField: "_id",
as: "newCategoryParent"
}},
{ $unwind: "$newCategoryParent"
},
{
$match: {
"newCategoryParent.categoryName": "News"
}}
]);
现在我的所有帖子的父类别都是“新闻”,无论子类别是什么
推荐阅读
- javascript - 在反应中访问dom元素
- python - Django admin 反向外键关系
- azure-devops - 指定的 Swagger 版本未知。Azure APIM ARM 模板
- javascript - 更新对象属性具有特定值的数组
- python - Pandas:根据除一行之外的其他多级列按组对最内列进行排序
- c# - 值未从 service-proxies.ts 文件传递到 Appservices.cs
- python - 如何为特定领域的表征学习任务训练一个 BERT 模型?
- reactjs - 如何使用reactjs“在警报框中显示表格行值”
- android - 星号红色未在 TextInputEditText 中显示
- rust - 为什么生成在 MPSC 通道上迭代的线程的程序永远不会退出?