Monday, 29 May 2017

MongoDB Calculating average ratings for each user

So I have a mongoose model defined as such:

freelancerSchema = mongoose.Schema({
 _id: { type: String, default: shortid.generate},
 fname: String,
 lname: String;
 ratings: [{
       rating: Number,
       employer: {
          type: String,
          ref: 'Employer'
           }
        }],
 ...
}]

This schema represents a mongoose model for a Freelancer collection. my question is: in a certain query I need to find all freelancers with all their data and calculate the average rating for each of them. in the end, I would get an array of freelancers, each having their own calculated average rating preferably stored in a new field "avg_rating" or something like that.

I've tried looking into the mongodb Aggregate but I honestly didn't understand much.

Thanks in advance and sorry if my explanation wasn't precise enough.



via Kyle Sentient

No comments:

Post a Comment