我正在使用NodeJS和mongoose。
我有两个名为配置文件和业务的集合,具有以下架构。
ProfileSchema = new Schema ({
first_name: {type: String, required: true},
last_name: {type: String, required: true},
age: {type: Number, required: true},
business_ids: [
{type: schema.Types.ObjectId, ref: 'business'}
]
});
相似地,
BusinessSchema = new Schema ({
title: {type: String, required: true},
type: {type: String, required: true},
address: {type: String, required: true},
});
我查询个人资料时的示例响应是
profiles.find().populate("business_ids")
回报
{
"_id": "5bf5fbef16a06667027eecc2",
"first_name": "Asad",
"last_name": "Hayat",
"age": "26",
"business_ids": [
{
"_id": "5ae14d2e124da839884ff939",
"title": "Business 1",
"type": "B Type",
"address": "Business 1 Address"
},
{
"_id": "5ae14d2e124da839884ff93b",
"title": "Business 2",
"type": "C Type",
"address": "Business 2 Address"
}
],
"__v": 0
}
我希望business_ids字段在集合中保持不变,但在我的查询响应中将其重命名为business。我怎样才能做到这一点。
您可以使用聚合管道 with$lookup
而不是 find with populate
像这样的东西
db.profile.aggregate([
{
$lookup: {
from: "business",
localField: "business_ids",
foreignField: "_id",
as: "businesses"
}
},
{
$project: {
business_ids: 0 // this is to remove the business_ids array of ObjectIds, if you want to keep it, you can omit this $project step
}
}
])
你可以在这里测试Mongo Playground
希望能帮助到你
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句