node.js - 如何在嵌套文档中查找记录?
问题描述
所以我正在学习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});
解决方案
你可以做这样的事情。
await CustomerModel.findOne({telegram_id: ctx.chat.id})
.populate({
path: 'subscriptions',
match: {status: 'active'}
});
这里path
用于加入下一个模型,match
用于在该模型内部进行查询。
推荐阅读
- json - 使用 JSON_VALUE + JSON_QUERY 创建新的 JSON
- matplotlib - 在 y 轴上添加科学记数法会改变 matplotlib 条形图中条形的高度
- jquery - 修复了 jQuery 数据表 ui 崩溃的 col
- apache-kafka - 在 Confluent Cloud 免费试用版中使用具有公共 id 列的 Data Gen 工具生成 2 个流
- html - 是否有引导程序自动隐藏不同媒体屏幕中的某些组件?
- javascript - Vuepress 从 .md 文件标题创建 H1
- azure - UNABLE_TO_VERIFY_LEAF_SIGNATURE 即使 SonarQube 位于应用程序网关后面并带有 SSL 终止
- javascript - 如何访问 css 以在 javascript Vue JS 中进行动画处理
- docker - RabbitMQ **WARNING** 由 docker-entrypoint.sh 生成
- c - 使用 write() 打印字母表