【问题标题】:Unable to query all the documents of a reference model that match a string instead of an id无法查询与字符串而不是 id 匹配的参考模型的所有文档
【发布时间】:2021-12-27 21:41:24
【问题描述】:

所以我正在开发一个应用程序,其中有两个模型,帖子和类别。在帖子中有一个引用类别模型的字段。现在有多个具有相同类别的帖子,我需要通过传递一个与类别名称匹配的字符串来获取这些帖子。我需要在这里使用聚合,因为有成千上万的帖子。并且需要花费大量时间来获取 90k 个帖子,然后与类别名称匹配以找到所有帖子。所以我想使用聚合来查找具有类别名称的类别,然后使用该类别的 id 来查找所有帖子。

假设这里是两个模式:

**POSTS SCHEMA** 

const postSchema = new mongoose.Schema( {
    text: {
        type: String
    },
    categories: [ {
        _id: false,
        categoryID: {
            type: mongoose.Schema.Types.ObjectId,
            ref: 'Categories',
        }
    } ]
} );

**CATEGORIES SCHEMA**

const categorySchema = new mongoose.Schema( {
    category: {
        type: String,
    }
} );

所以现在假设我需要找到所有类别名为Politics 的帖子。我无法获取所有帖子,然后根据类别名称过滤掉,因为由于帖子总数,提取需要很多时间。所以这就是我尝试过的:

const aggregateObj = [ 
            {
                "$lookup": {
                    "from": "categories",
                    "let": { 
                        "category": "$category"
                    },
                    "pipeline": [
                        { 
                            "$match": {
                                "category": "Politics"
                            }
                        }
                    ],
                    "as": "category"
                }
            },
            {
                $unwind: "$category"
            },
            {
                "$lookup": {
                    "from": "posts",
                    "pipeline": [
                        { 
                            "$match": {
                                "categories.categoryID": "$_id"
                            }
                        }
                    ],
                    "as": "posts"
                }
            }
];
    
const posts= await Post.aggregate( aggregateObj ).exec();

我没有得到任何输出,因为它一直在加载而没有任何错误。我在这里做错了什么?

【问题讨论】:

  • 您我想验证您的第一次$lookup 使用是否正常;例如,在您使用时,let 选项的用途是什么。
  • @prasad_ 我是从教程中得到的。我猜是分配一个变量。

标签: node.js mongodb mongoose aggregate


【解决方案1】:

您无需查找另一个集合,然后使用它来查找另一个集合中的数据。您可以填充帖子集合,然后匹配所需的字符串。像这样的:

const aggregateObj = [ 
      {
            '$lookup': {
                    'from': 'categories', 
                    'localField': 'categories.categoryID', 
                    'foreignField': '_id', 
                    'as': 'categories' // if you have a field with the same name then it will overwrite that and populate. Or you can just specify a different name
            }
      }, {
                '$match': {
                    'categories.category': 'Politics'
            }
      }
];

【讨论】:

    猜你喜欢
    • 2021-11-18
    • 1970-01-01
    • 2013-07-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-19
    相关资源
    最近更新 更多