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.