Reputation: 419
I have a collection as follows
// collection: appointments
{
"_id" : ObjectId("5c50682b663e854a1c2d9401"),
"status" : "Pending",
"discount" : 0,
"removed" : false,
"services" : [
{
"_id" : ObjectId("5c505a29af3a655b98812ca7"),
"service" : ObjectId("5c505a12af3a655b98812ca5"),
"cost" : 200
},
{
"_id" : ObjectId("5c50691ab9081f53287d2354"),
"service" : ObjectId("5c5069a600ec0d7a1800aa73"),
"cost" : 200
}
],
"doctor" : ObjectId("5c5059b2af3a655b98812ca1"),
"patient" : ObjectId("5c5059e5af3a655b98812ca4"),
"date" : ISODate("2018-11-12T00:00:00.000+02:00"),
"clinic" : ObjectId("5c5059d8af3a655b98812ca3"),
"diagnosis" : [ ],
"rx" : [ ],
"labs" : [ ],
"scans" : [ ],
"__v" : 0
}
I'm trying to aggregate that collection, but i want to populate services.service as it's an object id
let appointments = await Appointment.aggregate([
{ $lookup: { from: 'services',localField: 'services.service',foreignField: '_id',as: 'services' } },
{ $project: {
'date': 1 ,
'status': 1 ,
'services': 1 ,
} },
{ $limit: Number(req.query.limit) },
{ $skip: Number(req.query.skip) }
]);
what i'm getting
"appointments": [
{
"_id": "5c50682b663e854a1c2d9401",
"status": "Pending",
"discount": 0,
"paidAmount": 0,
"services": [
{
"_id": "5c505a12af3a655b98812ca5",
"removed": false,
"name": "kashf",
"clinic": "5c5059d8af3a655b98812ca3",
"updatedAt": "2019-01-29T13:50:10.651Z",
"createdAt": "2019-01-29T13:50:10.651Z",
"__v": 0
},
{
"_id": "5c5069a600ec0d7a1800aa73",
"removed": false,
"name": "arza3",
"clinic": "5c5059d8af3a655b98812ca3",
"updatedAt": "2019-01-29T14:56:38.314Z",
"createdAt": "2019-01-29T14:56:38.314Z",
"__v": 0
}
],
"date": "2018-11-11T22:00:00.000Z"
}
]
so i lost the cost attribute, also the id of the object array any solution for this ? i tried unwinding the services, but it results in two appointments objects with the same id
Upvotes: 0
Views: 184
Reputation: 419
I've got it
let appointments = await Appointment.aggregate([
{ $unwind: '$services' },
{ $lookup: { from: 'services',localField: 'services.service',foreignField: '_id',as: 'services.service' } },
{ $unwind: '$services.service' },
{
$group: {
'_id': '$_id',
'services': { $push: '$services' },
}
},
{ $project: {
'services': 1 ,
} },
]);
Upvotes: 1
Reputation: 107
u can use multiple populate lik that
CHAR.findOneAndUpdate({id: info.id}, char, {upsert: true, new: true})
.populate({path : 'intels', populate : {path : 'intels', populate : {path : 'from'}}})
.populate({path : 'alts', populate : {path : 'alts', populate : {path : 'intels', populate : {path : 'intels.from'}}}})
Upvotes: 0