2

Mongoose provides us with the ability to apply Aggregation Hooks which works only when aggregation is applied to that particular model.

userSchema.post("aggregate", function() {
this.pipeline().push({$project: { _id: 1, firstName: 1, lastName: 1 }});});

The above code works fine and proper projection is applied when we do

User.aggregate([...])

But the same projection is not applied when we lookup user in another model's aggregate.

{
    $lookup: {
      from: "users",
      localField: "user",
      foreignField: "_id",
      as: "associatedUser"
    }
  },

Is there a way in mongoose so that we can apply projection in model level which is applied where ever that model is accessed and we don't have to apply projection in every aggregation query.

Fakhir Shad
  • 1,071
  • 8
  • 20
  • @Ashh https://stackoverflow.com/users/7510657/ashh Sir My question has been marked as duplicate, but the question is different. My question is to apply projection at model level so that we don't have to apply projection in every query whenever we apply $lookup. Whereas the questions which were associated with it as it's duplicates are how to apply projection in $lookup and in the answer it is applied on query level i.e for each query. – Fakhir Shad Jan 13 '20 at 10:18
  • Then you need to create a custom function. I m reopening the question but do not think you can get anything related to this instead of using a custom function. – Ashh Jan 13 '20 at 10:22
  • You may use Uncorrelated quieries in $lookup (https://docs.mongodb.com/manual/reference/operator/aggregation/lookup/#join-conditions-and-uncorrelated-sub-queries) – Valijon Jan 13 '20 at 13:27

0 Answers0