Monday, 5 June 2017

MongooseJS populate and aggregate

i want to aggregate the ratings so i could get the total of feedbacks. But the thing is, it's referenced. Here's my schema

User

    username: String,
    fullname: String,
    email: {
        type: String,
        lowercase: true,
        unique: true
    },
  address: String,
  password: String,
  feedback: [{
      type: mongoose.Schema.Types.ObjectId,
      ref: 'Feedback'    
  }]

Feedback

var FeedbackSchema = new mongoose.Schema({
    postname: String,
    user: {
        type: mongoose.Schema.Types.ObjectId,
        ref: 'User'
    },
    message: String,
    feedbacktype: String,
    thumbsup: Boolean,
    rating: {
        communication: Number,
        timeliness: Number,
        delivery: Number
    }
});

So what i want to achieve is, i will find the User by id then populate the feedbacks field, then i will aggregate the ratings on the feedback field so i would get a total of number of ratings for communication, for delivery and for timeliness. (The ratings are 1-5 stars)

Do you know how to aggregate and populate? thank you



via John

No comments:

Post a Comment