我有三个相互关联的收藏
Partner
{
"_id": "5d68b91f0ef87f0c36ad1f7b",
"name": "1111 Vijay Dev",
}
Event {
"oneTime": true,
"_id": "5d6cfc09967a6f45c51d4375",
"title": "WelcomeOneEvent1",
}
User which contains data for both Partner and Event with Keys partnerId and eventId
{
"_id": ObjectId("5d68f06e3058326af09d6c53"),
"firstName": "Demo",
"partners": [
{
"_id": ObjectId("5d6cafd3e109107b83068657"),
"partnerId": ObjectId("5d4d60d6f45f1c6e723bc074")
}
],
"events": [
{
"_id": ObjectId("5d6cfc18967a6f45c51d437b"),
"eventId": ObjectId("5d6a4b882d267958eb82071c")
},
{
"_id": ObjectId("5d6cfc18967a6f45c51d437a"),
"eventId": ObjectId("5d6cfc09967a6f45c51d4375")
}
]
}
我需要获取具有用户的所有合作伙伴的列表以及这些用户的事件。
我尝试与用户一起获取partners数组,但成功,但是无法获取事件详细信息。下面是我的相同代码
partnerSchema.statics.chking = function() {
return new Promise((resolve, reject) => {
this.aggregate(
[
{
$lookup: {
from: 'users',
localField: '_id',
foreignField: 'partners.partnerId',
as: 'users'
}
},
{
$unwind:{
'path': '$user.events',
'preserveNullAndEmptyArrays': true
}
},
{
$lookup: {
from: 'events',
localField: 'users.events.eventId',
foreignField: '_id',
as: 'events'
}
},
{
$project: {
name: 1,
'users._id': 1,
'users.firstName': 1,
'users.events': '$events'
}
}
],
function(err, result) {
console.log('result', result)
if (err) return reject(err)
resolve(result)
}
)
})
}
实际结果是这样的。我需要添加缺少的事件详细信息,例如id和title:
{
"data": [
{
"_id": "5d68b91f0ef87f0c36ad1f7b",
"name": "1111 Vijay Dev",
"users": [
{
"_id": "5d6a144f498ea95bf51298ea",
"firstName": "Vijay one",
"events": []
},
{
"_id": "5d6a1459498ea95bf51298ec",
"firstName": "vijay 2",
"events": []
},
{
"_id": "5d6d046c0b6700548397e262",
"firstName": "check11",
"events": []
}
]
}
]
}
预期:
{
"data": [
{
"_id": "5d68b91f0ef87f0c36ad1f7b",
"name": "1111 Vijay Dev",
"users": [
{
"_id": "5d6a144f498ea95bf51298ea",
"firstName": "Vijay one",
"events": [
{ "_id": "5d6cfc09967a6f45c51d4374",
"title": "WelcomeOneEvent1"},
{ "_id": "5d6cfc09967a6f45c51d4375",
"title": "WelcomeTwoEvent2"},
]
},
{
"_id": "5d6a1459498ea95bf51298ec",
"firstName": "vijay 2",
"events": []
},
{
"_id": "5d6d046c0b6700548397e262",
"firstName": "check11",
"events": []
}
]
}
]
}
答案 0 :(得分:0)
请尝试:
Partner.aggregate([
{
$lookup: {
from: 'users',
localField: '_id',
foreignField: 'partners.partnerId',
as: 'users'
}
},
{
$unwind: {
'path': '$users',
'preserveNullAndEmptyArrays': true
}
},
{
$lookup: {
from: 'events',
localField: 'users.events.eventId',
foreignField: '_id',
as: 'events'
}
}, { $addFields: { 'users.events': '$events' } }, { $group: { _id: '$_id', users: { $push: '$users' }, data: { $first: '$$ROOT' } } }, { $addFields: { 'data.users': '$users' } },
{ $replaceRoot: { 'newRoot': '$data' } }, {
$project: {
name: 1,
'users._id': 1,
'users.firstName': 1,
'users.events': 1
}
}
])