node.js - Mongoose/Express : average of subdocuments -
i have 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 retrieve products along 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 add results "average" field contains average of comments each product results :
[{name: "product 1", _user: {name: "bob"}, average: 7.65},...]
is possible unique query ? need compute , store average in product document each time new comment added ?
thanks !
maybe should try calculating "running average". need know how many ratings there are, , average. having same average value saved every document in mongodb should bad practice, hope you. create schema this:
var averageproductratingschema = new schema({ productid: {type: schema.types.objectid, ref: 'product'}, averagerating: {type: number}, numberofratings: {type: number} });
then implement addrating() function this:
function addrating(newrating, productid) { /* find document holds average rating of wanted product */ averageproductrating.findoneasync({productid: productid}) .then(function (avgprodrating) { /* calculate new average using running average method. http://www.bennadel.com/blog/1627-create-a-running-average-without-storing-individual-values.htm */ var newaveragerating = (avgprodrating.averagerating * avgprodrating.numberofratings + newrating) / (avgprodrating.numberofratings + 1); var newnumberofratings = avgprodrating.numberofratings + 1; averageproductrating.update( { productid: productid }, { $set: { averagerating: newaveragerating, numberofratings: newnumberofratings } }); }); }
this link describes similiar issue: http://www.bennadel.com/blog/1627-create-a-running-average-without-storing-individual-values.htm
Comments
Post a Comment