gpt4 book ai didi

node.js - 如何在嵌套文档中查找记录?

转载 作者:太空宇宙 更新时间:2023-11-03 23:12:43 25 4
gpt4 key购买 nike

所以我正在学习 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
}
});

本质上我想返回客户的所有订阅,但如何在嵌套文档中搜索,在本例中是订阅

这是订阅模型:

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

我只想返回状态为有效的订阅,目前我可以通过以下方式搜索客户:

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

最佳答案

您可以使用filter聚合以在嵌套数组中进行过滤。

Playground

Mongoose 的快速路线示例:

router.get("/customers/:id", async (req, res) => {

let result = await Customer.aggregate([
{
$match: {
telegram_id: 1 //todo: req.params.id
}
},
{
$project: {
_id: "$_id",
stripe_id: "$stripe_id",
telegram_id: "$telegram_id",
email: "$email",
subscriptions: {
$filter: {
input: "$subscriptions",
as: "item",
cond: {
$eq: ["$$item.status", "active"]
}
}
}
}
}
]);

//todo: result will be an array, you can return the result[0] if you want to return as object
res.send(result);
});

假设我们有以下文档:

{
"_id" : ObjectId("5e09eaa1c22a8850c01dff77"),
"stripe_id" : "stripe_id 1",
"telegram_id" : 1,
"email" : "email@gmail.com",
"subscriptions" : [
{
"_id" : ObjectId("5e09eaa1c22a8850c01dff7a"),
"status" : "active",
"plan_id" : "plan 1"
},
{
"_id" : ObjectId("5e09eaa1c22a8850c01dff79"),
"status" : "passive",
"plan_id" : "plan 2"
},
{
"_id" : ObjectId("5e09eaa1c22a8850c01dff78"),
"status" : "active",
"plan_id" : "plan 3"
}
],
"created_at" : ISODate("2019-12-30T15:16:33.967+03:00"),
"__v" : 0
}

结果将是这样的:

[
{
"_id": "5e09eaa1c22a8850c01dff77",
"stripe_id": "stripe_id 1",
"telegram_id": 1,
"email": "email@gmail.com",
"subscriptions": [
{
"_id": "5e09eaa1c22a8850c01dff7a",
"status": "active",
"plan_id": "plan 1"
},
{
"_id": "5e09eaa1c22a8850c01dff78",
"status": "active",
"plan_id": "plan 3"
}
]
}
]

如果您不想逐一投影项目,可以使用addFields像这样的聚合:

router.get("/customers/:id", async (req, res) => {
let result = await Customer.aggregate([
{
$match: {
telegram_id: 1
}
},
{
$addFields: {
subscriptions: {
$filter: {
input: "$subscriptions",
as: "item",
cond: {
$eq: ["$$item.status", "active"]
}
}
}
}
}
]);

res.send(result);
});

关于node.js - 如何在嵌套文档中查找记录?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59530385/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com