this question has answer here:
- mongoose - how group , populate? 2 answers
i have 2 mongoose models: 1 transactions , other 1 tags associated them. in order implement reports, need aggregate code this:
transaction.aggregate([ { $unwind: '$tags' }, { $group: { _id: '$tags', amount: { $sum: '$amount' } } } ])
question
this produces output containing _id
, amount
. now, i'd populate other fields (e.g. name
) model, keeping calculated amount
column. can within simple populate
?
edit
the schemas models i'm describing:
var transactionschema = new schema({ description: { type: string, trim: true }, amount: { type: number, required: 'forneça um valor', }, date: { type: date, required: 'forneça uma data', default: date.now }, fromofx: { type: boolean, default: false }, created: { type: date, default: date.now }, correlated: { type: boolean, default: false }, tags: [{ type: schema.types.objectid, ref: 'transactiontag' }], correlates: [{ type: schema.types.objectid, ref: 'transaction' }], user: { type: schema.types.objectid, ref: 'user' } }); var transactiontagschema = new schema({ name: { type: string, required: 'forneça um nome', trim: true }, description: { type: string, trim: true }, amount: { type: number } });
you can populate aggregation after fetched data mongodb. this:
// aggregate query question transaction.aggregate([{ $unwind: '$tags' }, { $group: { _id: '$tags', amount: { $sum: '$amount' } } }]) .exec(function(err, transactions) { // don't forget error handling // callback transactions // assuming having tag model tag.populate(transactions, {path: '_id'}, function(err, populatedtransactions) { // populated translactions inside populatedtransactions }); });
Comments
Post a Comment