2016-10-10 29 views
2

我在mongoose一个模型,类似于此:我如何总结我的mongodb集合中的值?

var TestSchema = new Schema({ 
    test_username: {type: String, required: true}, 
    test_content: {type: String}, 
    reactions: [{ 
     test_username: {type: String, required: true}, 
     value: {type: Number, required: true}, 
     sent_at: {type: Date, required: true, default: Date.now} 
    }], 
    created_at: {type: Date, default: Date.now}, 
    updated_at: {type: Date, default: Date.now} 
}) 

它存储我Test物体与它的许多反应。每个反应包含1-1value和不同的用户名。 现在我正在尝试创建一个端点,该端点将Test id作为输入并返回其包含的所有反应的总计和总和。

我开始写它:

testRoutes.get('/:id/reactions/', functions.validateRequestsGET, function(req, res){ 
    var testId = req.params.id; 

    var query = Test... //here I'm stuck 

    query.exec(function(err, reactions){ 
     if(err) { 
      res.send(err); 
      return; 
     } 

     res.json(reactions); 
    }); 
}); 

你可以给我如何创建一个查询,可以返回我JSON与总结量的提示?像{reactions: 17}或类似的东西?

回答

1

试试这个:

Test.aggregate(
    { $match: { 
     _id: testId // you might want to convert this from string to ObjectId() 
    }},  
    { $project: { 
     sumReactions: { $sum: "$reactions.value" } 
    }} 
)