I’m new to firestore cloud functions. I’m trying to write a function that based on the change of one collection should be updated the data of another collection. I create cycle for on the ingredients, the update function works, but it assign the last value of the for cycle to the “total_amount” and “partial_amount”. I.e. I have the ingredient “Zucchini” with 20 as amount and “Tomato” with 50 as amount and the update function assign 50 to both the document in aggregate_ingrdients collection instead the corresponding one. Seems the cycle for and the update function are not in sync. Could be an issue of async function? How can I solve it?
Thanks,
Giuliana
Below my code:
// When any field on any document in course change (added or updated), the aggregate ingredient should be updated
exports.updateAggrIngr = onDocumentWritten("/course/{courseId}", (event) => {
// Save the data after the update/creation courseid
const v_recipeRef = event.data.after.data().recipeRef;
const v_servings = event.data.after.data().servings;
const v_userRef = event.data.after.data().userRef;
// Take the recipe information from the course changed
return v_recipeRef.get().then(recipe => {
const ingredients_LLM = recipe.data().ingredients_LLM;
for (let i in ingredients_LLM) {
console.log("1) Processing ingredient: "+ingredients_LLM[i]["name"]);
var v_ingr_name=ingredients_LLM[i]["name"];
var v_ingr_amount=ingredients_LLM[i]["amount"];
var v_AggrIngrRef=ingredients_LLM[i]["AggrIngrRef"];
// Increment total amount and partial amount of the ingredient
console.log("2) Increment total amount and partial amount of "+ v_ingr_amount+" for "+ v_ingr_name);
const aggr_ingr_docID = db.collection("aggregate_ingredients");
aggr_ingr_docID.where("name", "==", v_ingr_name).get().then(snapshots => {
if (snapshots.size > 0) {snapshots.forEach(orderItem => {
console.log("docID :"+ orderItem.id+", name: "+orderItem.data().name);
return aggr_ingr_docID.doc(orderItem.id).update({"total_amount": FieldValue.increment(v_ingr_amount),"partials.partial_amount":v_ingr_amount});
})
}
})
}
});
});