I have the following models :
Product :
var ProductSchema = new Schema({
name: String,
comments: [{ type: Schema.Types.ObjectId, ref: 'Comment'}],
_user: { type: Schema.Types.ObjectId, ref: 'User'}
});
Comment :
var CommentSchema = new Schema({
text: String,
rating: Number,
_product: { type: Schema.Types.ObjectId, ref: 'Product'}
});
What I do currently is retrieve all Products along with their user :
router.get('/', function(req, res, next) {
Product.find().populate('_user').exec(function (err, products) {
if (err) return next(err);
res.json(products);
});
});
I'd like to add to the results an "average" field that contains the average of all comments for each product so the results would look like this :
[{name: "Product 1", _user: {name: "Bob"}, average: 7.65},...]
Is this possible with a unique query ? Do I need to compute and store the average in the Product document each time a new Comment is added ?
Thanks !
Aucun commentaire:
Enregistrer un commentaire