【问题标题】:mongoose - I want to find a documents that contain a nested reference?mongoose - 我想查找包含嵌套引用的文档?
【发布时间】:2021-11-03 21:33:25
【问题描述】:

我是 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.js mongodb mongoose


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 2014-08-05
      • 2012-01-15
      • 2021-02-21
      • 2012-06-23
      • 2012-10-17
      • 2020-10-04
      • 2017-05-13
      • 1970-01-01
      • 2016-04-25
      相关资源
      最近更新 更多