I am trying to do a relative simple API which returns recipes with summarized attributes of kcal, carbs, proteins, etc.
So lets lay it out in a simplistic way, currently I have three models.
Recipe
name: String
ingredients: [{type: mongoose.Schema.Types.ObjectId, ref: 'Ingredient'}]
Ingredient
weightInGrams: Number
nutrient: {type: mongoose.Schema.Types.ObjectId, ref: 'Nutrient'}
Nutrient
name: String
kcalPerHundredGrams: Number
So lets say I want to create a Recipe of 1kg of cheese, th en I would have a Nutrient with the name of Cheese and with a kcalPerHundredGrams of 493kcal. I then create an ingredient with a ref to my Cheese-nutrient and a weightInGrams of 1000. Last part is creating the Cheese-recipe with a ref to my newly created ingredient.
All this is easily done and possible. However, when I fetch all the Recipes with Recipe.find(), I want the Recipes to have an attribute called 'kcal' which is the sum of all ingredients kcal for that Recipe.
In this case we only have one ingredient so the Recipe would have an attribute of kcal calculated to 493 * 10 = 4930 since my nutrient is 493kcals per 100g and my ingredient is 1kg (10 times 100g).
This is how far I've gotten:
var query = Recipe.aggregate([
{
$lookup: {
from: 'ingredients',
localField: 'ingredients',
foreignField: '_id',
as: 'ingredients'
},
},
{
$addFields: {
weight: {
$sum: '$ingredients.weightInGrams'
}
}
}
]);
This sums up the total weight of the recipe and it works just fine. However I also want to add the sum of all kcals of the ingredients, which mean that I need to lookup the nutrient for each ingredient in order to calculate the total kcals (nutrients kcalPerHundredGrams divided by 100 and then multiplied with ingredients weightInGrams), I cannot seem to understand how to do this nested lookup against only one document (an ingredient only has one nutrient)?