我是 Firestore 云函数的新手。我正在尝试编写一个函数,该函数应根据一个集合的变化更新另一个集合的数据。我为原料创建了循环...
我是 Firestore 云函数的新手。我正在尝试编写一个函数,该函数应根据一个集合的变化来更新另一个集合的数据。我在配料上创建了循环,更新函数可以工作,但它将循环的最后一个值分配给 \'total_amount\' 和 \'partial_amount\'。例如,我有配料 \'Zucchini\',其数量为 20,\'Tomato\',其数量为 50,更新函数将 50 分配给aggregate_ingrdients 集合中的两个文档,而不是相应的文档。似乎循环和更新函数不同步。可能是异步函数的问题吗?我该如何解决?
谢谢,朱莉安娜
下面是我的代码:
// 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});
})
}
})
}
});
});