Skip to content Skip to sidebar Skip to footer

Mongoose Sum Fields From Populated Documents

I have two models: User and Track. User can complete and get points for every Track. User schema: let userSchema = new mongoose.Schema({ name: {type: String, required: true},

Solution 1:

You can try below aggregation in 3.4.

$lookup to look up the points for completed tracks followed by $addFields to return a score field summing the points and $project with exclusion to drop the lookup-data field from response.

UserModel.aggregate([
  {"$lookup":{
    "from":"tracks", // name of the foreign collection"localField":"completedTracks",
    "foreignField":"_id",
    "as":"lookup-data"
  }},
  {"$addFields":{
    "score":{
      "$sum":"$lookup-data.points"
    }
  }},
  {"$project":{"lookup-data":0}}
])

Post a Comment for "Mongoose Sum Fields From Populated Documents"