2

这是我第一次看到对 node.js 和 mongodb 的愤怒,所以我可能做了一些愚蠢的事情或错过了一些明显的事情,但是鉴于下面的文档和查询,为什么会返回一个空对象?

1 文档示例

{  
    __v: 0, 
    _id: ObjectId("50bf7f12fc71b74f3b000001"),
    amount: 452.23, 
    categoryId: 13, 
    created: ISODate("2012-12-05T17:06:26Z"), 
    description: "Test", 
    typeId: 1, 
    updated: ISODate("2012-12-05T17:06:26Z")
}

2 问题代码

var Schema = mongoose.Schema;  

var Expense = new Schema({  
    description: { type: String, required: true },  
    amount: { type: Number, required: true },  
    created: { type: Date, default: Date.now },
    updated: { type: Date, default: Date.now },
    categoryId: { type: Number, required: true },
    typeId: { type: Number, required: true }
});

var ExpenseModel = mongoose.model('Expense', Expense);

ExpenseModel.aggregate(  
    { $group: { _id: '$typeId', total: { $sum: '$amount' }}}, 
    function (err, summary) {
        if(err){
            return res.send(500, { error: err }); 
        }

        if(summary) {
            return res.send(summary);
        } else {
            res.send(500, { error: 'couldnt find expenses' }); 
        }
    }
);
4

2 回答 2

4

确保您的模型引用了正确的集合,并且您$group$project. 这是一个完整的例子:

var db = mongoose.createConnection('localhost:27017/myDatabase');

var expenseSchema = new mongoose.Schema({
    description: { type: String, required: true },  
    amount: { type: Number, required: true },  
    created: { type: Date, default: Date.now },
    updated: { type: Date, default: Date.now },
    categoryId: { type: Number, required: true },
    typeId: { type: Number, required: true }
});

var Expense = db.model('expenses', expenseSchema); // make sure the first argument matches your collection's name

Expense.aggregate(  
    { $group: { _id: '$typeId', expense: { $sum: '$amount' }}}, // 'group' goes first!
    { $project: { _id: 1, expense: 1 }}, // you can only project fields from 'group'
    function(err, summary) {
        console.log(summary);
    }
);

这应该会为您提供一个基于“typeId”汇总所有费用的输出:

[
    { _id: 1, expense: 300.00 },
    { _id: 2, expense: 45.00 },
    ...
]

我刚刚学习了聚合来回答这个问题,所以如果有什么问题请告诉我。

于 2012-12-09T15:19:24.393 回答
1

将集合的名称从费用更改为费用解决了这个问题。

于 2012-12-09T20:20:09.270 回答