Populate before aggreagte

Hi there,

I have two collections:

  • Users
  • Orders

The orders have a key user data type ObjectId referencing a user.

I would like to do an aggregate search through the orders AND the users within.

Something like this ( doesn’t work ):

const { search } = req.params
let orders = await Orders.aggregate([
          '$search': {
            'index': 'ranges',
            'text': {
              'query': search,
              'path': {
                'wildcard': '*'
      orders = await Orders.populate(orders, { path: "user productsBought.range" })

But like this I am populating after finding, which is not finding orders by user name.

Any help is appreciated.


Hi @Toni_Enguix I never saw this one. Sorry for being so late. Also, welcome to the forum. We intend to be more timely in the future.

I have a few questions to ensure I can give you the best answer.

  1. Could you share a sample document with mock data for each of the collections?
  2. It looks like the only collection queried here is orders. To clarify, do you want to add users to the orders collections?
  3. Why did you choose a query across all the fields?

I ended up including the user in the order’s model so that’s sorted. But I’ll try to answer this! I think it’s worth a look. Thanks for answering, better late than never. I closed this project but I’ll look for it and try to answer (Y)