首页 > 解决方案 > 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'});

但我有一个空数组[]。有没有办法找到包含参考参考的文件?

标签: node.jsmongodbmongoose

解决方案


我通过使用 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"
    }}
  ]);

现在我的所有帖子的父类别都是“新闻”,无论子类别是什么


推荐阅读