我有四个集合person、other_details、职业_details、bank_details
,如下所述
person =>[
{
id : 1,
name : 'john',
other_details : 1023
},
{
id : 2,
name : 'mark',
other_details : 99
}
]
other_details => [
{
id: 1023,
married: false,
occupation_details: 144,
bank_details : 10
},
{
id: 99,
married: true,
occupation_details: 45,
bank_details : 11
}
]
occupation_details => [
{
id: 144,
comp_name : 'oscorp inc.'
},
{
id: 45,
comp_name : 'tesla inc.'
}
]
bank_details => [
{
id: 10,
bank : 'Bank of canada'
},
{
id: 11,
bank : 'Peoples bank of canada'
}
]
我正在使用 mongoose 库和 Nodejs
// id = 1
person.findById(id).populate({
path: 'other_details',
populate: [
{
path: 'occupation_details'
},
{
path: 'bank_details'
}
]
})
因此上述查询的结果如下所示 =>
{
id : 1,
name : 'john',
other_details : {
id: 1023,
married: false,
occupation_details: {
id: 144,
comp_name : 'oscorp inc.'
},
bank_details : {
id: 10,
bank : 'Bank of canada'
}
}
}
但由于某些原因,我想要如下所示的结果
{
id : 1,
name : 'john',
other_details : {
id: 1023,
married: false,
occupation_details: {
id: 144,
comp_name : 'oscorp inc.'
},
bank_details : 10,
custom_bank_details : {
id: 10,
bank : 'Bank of canada'
}
}
}
我需要的更改如下,bank_details
对象应该与 id 一起存在,并且来自其他集合的填充的 bank_details
数据应该以其他对象名称作为 自定义银行详细信息
bank_details : 10,
custom_bank_details : {
id: 10,
bank : 'Bank of canada'
}
最佳答案
更新:
您可以使用 virtual 将银行详细信息填充到新字段中。类似的东西
OtherDetailsSchema.virtual('custom_bank_details', {
ref: 'BankDetails',
localField: 'bank_details',
foreignField: '_id',
justOne: true
});
Person.findById(id).populate({
path: 'other_details',
populate: [
{path: 'occupation_details'},
{path: 'custom_bank_details'}
]})
原文
我不是 Mongoose 用户,所以我不确定是否可以填充新的字段名称。如果可行的话,您可以很容易地使用聚合和查找来实现。
类似于
person.aggregate([
{"$lookup":{
"from":"other_details",
"let":{"other_details":"$other_details"},
"pipeline":[
{"$match":{"$expr":{"$eq":["$id","$$other_details"]}}},
{"$lookup":{
"from":"occupation_details",
"localField":"occupation_details",
"foreignField":"id",
"as":"occupation_details"
}},
{"$unwind":"$occupation_details"},
{"$lookup":{
"from":"bank_details",
"localField":"bank_details",
"foreignField":"id",
"as":"custom_bank_details"
}},
{"$unwind":"$custom_bank_details"},
],
"as":"other_details"
}},
{"$unwind":"$other_details"}
])
关于mongodb - 需要在 mongodb 中使用自定义结果填充 block 中所需的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61184182/