首页 > 解决方案 > Node.js - 如何在 MongoDB 中的填充字段上应用过滤器和文本搜索?

问题描述

const parentSchema = new Schema({
  name: {
    type: String,
    required: true
  },
  childId: {
    type: Schema.Types.ObjectId,
    ref: "Child"
  }
});

const childSchema = new Schema({
  name: {
    type: String,
    required: true
  },
  email: {
    type: String,
    required: true
  }
});

const results = await Parent.find().populate("clientId", "email, name");
  1. 如何对“电子邮件”应用过滤器,以便填充具有给定“电子邮件”的特定孩子?
  2. 如何对孩子的“姓名”应用文本搜索?

标签: node.jsmongoosemongoose-populate

解决方案


您必须使用aggregate来实现这一点,请参见下面的代码

Parent.aggregate([
    {
        $lookup: {
            from: 'child',
            let: {
                email_: "abc@example.com",
                childId_: '$childId'
            },
            pipeline: [
                {
                    $match: {
                        $expr: {
                            $and: [
                                {
                                    $eq: ['$email', '$$email_']
                                },
                                {
                                    $eq: ['$_id', '$$childId_']
                                }
                            ]
                        }
                    }
                }
            ],
            as: 'child'
        }
    },{
        $unwind:'$child'
    },{
        $match:{
            'child.name':{
                $regex: "SearchKeyWord",
                $options: 'i' // For case insensitive search
            }
        }
    }
]);

在这里,我们首先填充仅child指定email_id使用$lookup

然后,我们使用正则表达式过滤child基于搜索关键字(我使用不区分大小写)

现在,这将为您提供所有具有各自父母的孩子的列表,例如[{parent_field_1:parent_value_1,......, child:{child_object}}]

如果您想要同一父母的所有孩子,您可以$group在后续投影中使用


推荐阅读