Before you guys saying that's a duplicated question a looked a few although I found an helpful one I still didn't make it work.
So I have this query:
const allRequestsFromThisEvent = await Request.aggregate([
{
$group: {
_id: "$telephone",
firstName: { $first: "$firstName" },
lastName: { $first: "$lastName" },
song: { $first: "$song" },
},
},
]);
Which retrun this:
[
{
_id: '+1 (307) 717-8457',
firstName: 'Tiago',
lastName: 'Pereira',
song: new ObjectId("636eca1f91b5d68164c29902")
},
{
_id: '+1 (533) 427-4934',
firstName: 'Alan',
lastName: 'Mcknight',
song: new ObjectId("636eca1f91b5d68164c29902")
},
{
_id: '+1 (955) 668-1608',
firstName: 'Mia',
lastName: 'Reed',
song: new ObjectId("636eca1f91b5d68164c29902")
},
{
_id: '+1 (273) 598-7287',
firstName: 'Garth',
lastName: 'Stone',
song: new ObjectId("636eca1f91b5d68164c29902")
}
]
So far so good, although I want to populate the song field.
I tried this example: Populate + Aggregate in Mongoose, which resulted in:
const allRequestsFromThisEvent = await Request.aggregate([
{ $unwind: "$song" },
{
$group: {
_id: "$telephone",
firstName: { $first: "$firstName" },
lastName: { $first: "$lastName" },
song: { $first: "$song" },
},
},
]).exec(function (err, song) {
Song.populate(song, { path: "song" }, function (err, populatedSong) {
console.log(populatedSong);
});
});
And the console.log of populatedSong
actually works as expected... although if I return the populatedSong
the console.log of allRequestsFromThisEvent
it is undefined...
What am I doing wrong?