【发布时间】:2014-04-22 02:06:23
【问题描述】:
因此,当我发出 DELETE 请求时,我正在更新我的模型并删除选定的数组项。然后我通过 ajax 将更新的 JSON 数据发回。我正在使用聚合方法来确定数组中选定值的总和,但问题是聚合方法在删除列表项之前根据可用的数据返回数据,即使我将它放在回调中也是如此。那么我怎样才能得到正确的更新总和呢?这是我正在使用的代码:
regUser.findOneAndUpdate(
{ username:req.user.username },
{ $pull: { budgets : { uniqueId: parseFloat(req.param('id')) }} },
function(err, data){
if(err) return console.log(err);
regUser.aggregate([
{ $match : { username : req.user.username } },
// Unwind the array to de-normalize the items
{ "$unwind": "$budgets" },
// Group the totals with conditions
{ "$group": {
"_id": "$_id",
"expense": { "$sum": {
"$cond": [
"$budgets.expense",
"$budgets.value",
0
]
}},
"nonExpense": { "$sum": {
"$cond": [
"$budgets.expense",
0,
"$budgets.value"
]
}}
}}], function(err, aggData){
sumData = aggData
});
res.json({
sumData: sumData,
budgetList: data.budgets
});
});
【问题讨论】: