i'm using nodejs + mongoosejs mongodb 2.6. have static function on model sums value of items in collection. each item assigned project using projectno property. need static function able give me total collection, , if projectno argument passed, add $match pipeline operator aggregation. save me having make 2 static functions same thing.
to spice things bit use bluebird promisifyall method make aggregation framework return promise.
my static function sums entire collection:
db.collection.aggregateasync([ {$group:{_id: null, amount: { $sum: "$amount" }}} ])
my static function sums records matching projectno:
db.collection.aggregateasync([ {$match: { projectno: projectno }}, {$group:{_id: null, amount: { $sum: "$amount" }}} ])
i want use aggregate.append method append $match pipeline if req.params.projectno included.
when try add async aggregation gets error, makes sense because promise. if try this:
db.collection.aggregateasync([ {$group:{_id: null, amount: { $sum: "$amount" }}} ]).then(function(aggregate){ aggregate.append({$match: { projectno: projectno }}) })
i error, (append undefined). how should go doing this? or live fact have 2 functions same thing?
i read source code in mongodb see how use aggregate.append method. if you're building aggregation using chained methods, can use append add pipeline operations.
so did instead put array of aggregation pipelines array. if there projectno add $match pipeline array using unshift(). used unshift because want $match pipeline first limit number of records, rest of pipeline operations.
var pipeline = [{$group:{_id: null, amount: { $sum: "$amount" }}}]; if(req.params.projectno){ pipeline.unshift({$match: { projectno: req.params.projectno }}); } db.collection.aggregateasync(pipeline);
i make things way more complicated need to...