0

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?

  • You may try to await the populate process. await Song.populate(...). If doesn't work, try to do this after .then like that : await Request.aggregate([...]).then(res=> await Song.populate(res, {...}) ... After that try to console allRequestsFromThisEvent. Hope, it will be helpful. – Onur Doğan Nov 12 '22 at 11:09
  • 2
    you can try `$lookup` inside the aggregation after the `$group`, populate as far as i know is slow join done on the application, it was useful before mongodb added the `$lookup` – Takis Nov 12 '22 at 11:58
  • 1
    I'd second the $lookup, I'm not at a computer right now, but here is a playground you could use as a base - https://mongoplayground.net/p/xZ4CLVIhdK3 – dangarfield Nov 12 '22 at 13:14
  • I tried the $lookup but didn’t make it work… also i don’t understand the $project thing – Tiago Pereira Nov 12 '22 at 15:11

0 Answers0