首页 > 解决方案 > 如何在嵌套文档中查找记录?

问题描述

所以我正在学习mongoose,我已经实现了Customer这样的模型:

let CustomerSchema = new Schema({
    stripe_id: {
        type: String,
        required: true
    },
    telegram_id: {
        type: Number
    },
    email: {
        type: String,
        required: true
    },
    subscriptions: [SubscriptionSchema],
    created_at: {
        type: Date,
        default: Date.now,
        required: true
    }
});

本质上,我想返回客户的所有订阅,但在这种情况下,如何在嵌套文档中搜索subscriptions

这是订阅模型:

let SubscriptionSchema = new Schema({
    status: {
        type: String,
        required: true
    },
    plan_id: {
        type: String,
        required: true
    }
});

我只想返回状态为的订阅,active目前我可以搜索客户:

let customer = await CustomerModel.findOne({telegram_id: ctx.chat.id});

标签: node.jsmongodbmongoose

解决方案


你可以做这样的事情。

await CustomerModel.findOne({telegram_id: ctx.chat.id})
      .populate({
         path: 'subscriptions',
         match: {status: 'active'}
 });

这里path用于加入下一个模型,match用于在该模型内部进行查询。


推荐阅读