我有两种不同的模型:
每个促销都有一个字段,其中包含对标记ID的引用。这在我的架构中引用并且工作正常:
const PromotionSchema = mongoose.Schema({
tags: { type: mongoose.Schema.Types.ObjectId, ref: 'Tag' }
}, { collection: 'promotions' });
我的问题是如何创建自定义响应,按标记对所有促销进行分组?像这样:
{
"tag": {
"_id": "999",
"value": "Lorem Ipsum"
},
"promotions": [{
"_id": "0001",
"value": "Value of promotion Nº1"
},
{
"_id": "0002",
"value": "Value of promotion Nº2"
},
... And the others that have the same Tag ID assigned
]}
}
现在,我正在使用Vanilla Javascript获取所有促销和过滤功能。我需要知道如何使用Mongoose来改善这一点。
答案 0 :(得分:0)
您可以尝试以下聚合函数来实现结果......
如果你有mongodb版本 3.6
db.promotion.aggregate([
// stage 1
{ "$lookup": {
"from": Promotions.collection.name,
"let": { "tags": "$tags" },
"pipeline": [
{ "$match": { "$expr": { "$eq": [ "$_id", "$$tags" ] } } }
],
"as": "tags"
}},
// stage 2
{ "$addFields": {
"tags": { "$arrayElemAt": [ "$tags", 0 ] }
}},
// stage 3
{ "$group": {
"_id": "$tags._id",
"promotions": {
"$push": {
"fieldName1": "$fieldName1",
"fieldName2": "$fieldName2",
}
}
}}
])
如果你有 3.6 之前的mongodb版本
db.promotion.aggregate([
{ "$lookup": {
"from": Promotions.collection.name,
"localField": "tags",
"foreignField": "_id"
"as": "tags"
}},
{ "$unwind": "tags" },
{ "$group": {
"_id": "$tags._id",
"promotions": {
"$push": {
"fieldName1": "$fieldName1",
"fieldName2": "$fieldName2",
}
}
}}
])
两者都会提供类似的输出
{
"tag": {
"_id": "999",
"value": "Lorem Ipsum"
},
"promotions": [{
"_id": "0001",
"value": "Value of promotion Nº1"
},
{
"_id": "0002",
"value": "Value of promotion Nº2"
}
]}
}