1

I want to run aggregation on Plan Schema and fetch a Feedback that has reference Id planId. But If I want to populate with lookup I need the reference ID in Plan but I don't like this strategy of saving reference Id, I like everything seperated.

Is there any way to populate without having reference Id.

something like this. but It doesn't work.

const pipe = [
{
  $lookup: {
    from: 'Feedbacks',
    pipeline: [
      { 
        $match: { 
          planId: '$_id'
        }
      }
    ],
    as: 'feedback'
  }
}]
await Plan.aggregate(pipe);
export interface Plan {
  _id: ObjectId;
  ...

}
export interface Feedback {
  planId: ObjectId;
  ...
}

Eric Aska
  • 611
  • 5
  • 14

1 Answers1

2

I found the answer. for anyone else:

{
  from: 'Feedbacks',
  let: { planIdInPlan:"$_id"},
  pipeline: [
              {
                $match: {
                  $expr:
                  {
                    $eq:['$planId', '$$planIdInPlan'] 
                  }
                }
                }
            ],
  as: 'feedback'
}
Eric Aska
  • 611
  • 5
  • 14
  • just one question, is not it a very bad with slow speed and worse performance? or it will be better to lookup from the right way (run the aggregate on feedback collection and lookup the plan collection), and then add more pipelines? – Kasir Barati Nov 28 '21 at 13:32
  • 1
    @KasirBarati I don't know man, I gave up on mongoose and its typings. realized NoSQL isn't my thing so changed to Postgresql completely. – Eric Aska Nov 28 '21 at 14:06