2017-05-04 5 views
0

上の原因となるエラーを減らす$使い方日々の食事日誌は、総消費カロリーを算出するために取得する:は、しかし、今私は、ライブサーバーにコードを展開しているとイムは今エラーを取得し、私は私の地元のホストされた開発中に機能を減らす使用していたサーバー

user_food.aggregate({$match:{user_id:mongoose.Types.ObjectId(req.session.user_id)}},{$project: {date:1,calories:{$add:[ 
         {$reduce: {input: "$breakfast",initialValue: 0,in: { $add : ["$$value", "$$this.calories"]}}}, 
         {$reduce: {input: "$lunch",initialValue: 0,in: { $add : ["$$value", "$$this.calories"]}}}, 
         {$reduce: {input: "$snacks",initialValue: 0,in: { $add : ["$$value", "$$this.calories"]}}}, 
         {$reduce: {input: "$dinner",initialValue: 0,in: { $add : ["$$value", "$$this.calories"]}}}]}}}, function (err, results) { 
     //if there is an error 
     if (err) { 
      console.log("something went wrong: " + err); 
      return res.status(500).send(err); 
     } else { 
      return res.status(200).send(results); 
     } 
    }); 

ユーザー食糧のためのドキュメントは非常に簡単です:

{ 
"_id": ObjectId("58d26c3dd60bd36f40fa0498"), 
"user_id": ObjectId("587cd30bd338b90a6c18e58f"), 
"calories": 2000, 
"date": 20170222, 
"snacks": [ 
    { 
    "nutrients": { 
    "protein": 7.5, 
    "carbs": 56.5, 
    "fat": 10.5 
    }, 
    "servings": 23.8, 
    "calories": 526, 
    "name": "Dairy milk" 
} 
], 
"dinner": [ ], 
"lunch": [ 
{ 
    "nutrients": { 
    "protein": 9.5, 
    "carbs": 25.4, 
    "fat": 17.2 
    }, 
    "servings": 60, 
    "calories": 751, 
    "name": "2 pork sausages rolls" 
} 
], 
"breakfast": [ 
{ 
    "nutrients": { 
    "protein": "4.8", 
    "carbs": "65", 
    "fat": "26" 
    }, 
    "servings": 20.5, 
    "calories": 438, 
    "name": "Oreo" 
} 
], 
"__v": 0 
} 

誰かがこのIDを修正する正しい方向に私を指すことができる場合は非常に感謝しています。

+0

$を減らすバージョン3.4で新たに追加されました。私たちのmongoシェルでdb.version()を実行してdbバージョンを確認できますか? –

+0

@Blastfreakバージョン2.6.12、これを修正して古いバージョンで動作させる方法はありますか? –

+0

基本的には3.4に導入されているので、最も安定した回避策はアップグレードすることです。 –

答えて

1

2.6 mongoバージョンでは、以下の集計を試すことができます。 $size

$projectは$日のすべての組み込みの配列と$グループのために$unwind続い{ calories: 0 }を持つすべての空の配列を交換すると$は、すべてのカロリーを追加します。 $project部分の詳細については

user_food.aggregate(
{$project: 
    { 
     date:1, 
     breakfast :{ $cond: [{$eq: [{$size: "$breakfast"}, 0] }, [ { calories: 0 } ], "$breakfast"] }, 
     lunch :{ $cond: [{$eq: [{$size: "$lunch"}, 0] }, [ { calories: 0 } ], "$lunch"] }, 
     snacks :{ $cond: [{$eq: [{$size: "$snacks"}, 0] }, [ { calories: 0 } ], "$snacks"] }, 
     dinner :{ $cond: [{$eq: [{$size: "$dinner"}, 0] }, [ { calories: 0 } ], "$dinner"] } 
    } 
}, 
{$unwind:"$breakfast"}, 
{$unwind:"$lunch"}, 
{$unwind:"$snacks"}, 
{$unwind:"$dinner"}, 
{$group:{_id:"$date", calories:{$sum:{ $add: [ "$breakfast.calories", "$lunch.calories","$snacks.calories", "$dinner.calories"] }} 
}} 
) 

$unwind empty array

関連する問題