0

i want to sum each values of ObjectId field in relationship with moongose.. I have this:

`var wineSchema = new Schema({
  name:         { type: String },
  code:         { type:String},
  type:         {
                    type: String,
                    enum: ['Red','Rose','White']
                },
  winery:       { type: String },
  grape_type:   { type: String },
  year:         { type: Number },
  alcohol:      { type: Number },
  rates:  [{ type: Schema.ObjectId, ref: "Rate" }],
  Comments:  [{ type: Schema.ObjectId, ref: "Comment" }],
});`

And this:

`var rate = new Schema({
  user  : { type: Schema.ObjectId, ref: "User" },
  userName  : {type: String},
  wineName  : { type: String},
  rating    : { type: Number}
});`

I want sum total values of each rate.rating inside wineSchema.rates.. How can I do it?

Adri Feria
  • 11
  • 1
  • 1
  • 4
  • The data is in another collection, and since MongoDB does not "really" do joins then something like mongoose `.populate()` essentially must retrieve "all" of the related data to the client before any "sum" can occur. If you have MongoDB 3.2 then you can apply `$lookup` as shown [here](http://stackoverflow.com/questions/34967482/lookup-on-objectids-in-an-array/34968489#34968489) – Blakes Seven Mar 15 '16 at 23:20
  • Ops.. can i get the average of every `rate.rating` for each wine with mongoose? – Adri Feria Mar 16 '16 at 18:35
  • hey @BlakesSeven thanks you so much for your help. I've finally done it. Using $ lookup and $ group + $ avg. Thankss!! =) – Adri Feria Mar 17 '16 at 20:59

0 Answers0