问题
Client side platform I am using is Web Angular.
Brief explanation: when I create a Task, I add followers in it, for example 3 followers.
Now once Task is saved. I want to push 3 records in 3 different documents.
- Do I create a for loop at client side?
- Use Firestore triggers? It's in beta and can take up to 10 seconds delay
- Firestore functions ?
Please share your best experience to cope up with this requirement.
Edit 1
How do I arrange the array union code in batch commit ?
My current code
var washingtonRef = firebase.firestore().collection("notifications").doc(this.loggedInuser);
washingtonRef.update({
notifyArray: firebase.firestore.FieldValue.arrayUnion(
{ food: "Margarita", ctg: "Pizza" },
{ food: "Chicken Burger", ctg: "Burger" },
{ food: "Veg Burger", ctg: "Burger" }
)
});
In batch
batch_write(){
// Get a new update batch
var batch = firebase.firestore().batch();
var sfRef = firebase.firestore().collection("notifications").doc("1");
batch.update(sfRef, **HOW DO I PLACE here arrayUnion like above** ??);
//another update batch
// and another update batch
// Commit the batch
batch.commit().then(function () {
console.log("batch commited successful");
});
}
If i am doing it like below, it gives error Cannot find name 'notifyArray'. -
var sfRef = firebase.firestore().collection("notifications").doc("1");
batch.update(sfRef,
notifyArray: firebase.firestore.FieldValue.arrayUnion(
{ food: "Margarita", ctg: "Pizza" },
{ food: "Chicken Burger", ctg: "Burger" },
{ food: "Veg Burger", ctg: "Burger" }
)
);
回答1:
The easiest way would be to use a batched write to write/update the four documents (writing the Task one and writing/updating the three followers documents).
You have to do as follows:
var batch = firebase.firestore().batch();
var sfRef = firebase.firestore().collection("notifications").doc("1");
batch.update(sfRef,
{ notifyArray: firebase.firestore.FieldValue.arrayUnion(
{ food: "Margarita", ctg: "Pizza" },
{ food: "Chicken Burger", ctg: "Burger" },
{ food: "Veg Burger", ctg: "Burger" }
)
}
);
var sfRef = firebase.firestore().collection("notifications").doc("2");
batch.update(sfRef,
{ notifyArray: firebase.firestore.FieldValue.arrayUnion(
{ food: "Margarita", ctg: "Pizza" },
{ food: "Chicken Burger", ctg: "Burger" },
{ food: "Veg Burger", ctg: "Burger" }
)
}
);
batch.commit().then(function () {
console.log("batch commited successful");
});
来源:https://stackoverflow.com/questions/61487697/design-decision-between-firestore-functions-or-triggers