当使用mongoose在mongodb中执行聚合时,返回一个空对象,为什么会这样?

时间:2012-12-09 09:51:48

标签: node.js mongodb mongoose

这是我第一次看到愤怒的一个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' }); 
        }
    }
);

2 个答案:

答案 0 :(得分: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 },
    ...
]

我刚刚学会了聚合来回答这个问题,所以告诉我是否有任何问题。

答案 1 :(得分:1)

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