I'm trying to create a save transaction with Flutter / Dart and Firestore which does the following:
A single document looks like this:
{
"title": "Some title",
"position": 1
}
In the documentation (https://firebase.google.com/docs/firestore/manage-data/transactions) I found explanation on how to make a save transaction on a single document but not on how to create this "two-step-atomic-transaction" that I need to save insert and update in a collection.
Maybe anyone has a hint for me?
Update: Thanks for your input Frank. Here is a code snippet which hopefully explains what I want to achieve:
@override
Future addCatalogItem(CatalogItem catalogItem) {
return firestore.runTransaction((Transaction transaction) async {
// Update position (++) of existing catalogItems
await firestore
.collection(path)
.where("catalogId", isEqualTo: catalogItem.catalogId)
.snapshots()
.forEach((snapshot) {
snapshot.documents.forEach((document) {
// document.reference.updateData({"position": document.data["position"]});
transaction.update(document.reference, {"position": document.data["position"] + 1});
});
});
// Add the new catalogItem at position 1
await firestore
.collection(path)
.document(catalogItem.id)
.setData(catalogItem.toJson());
});
}
A transaction can't contain a query. So you will need to first run a query to find the matching documents, and then get-and-update each document within the transaction. Aside from that it should be fairly straightforward.
Loop over the affected documents and for each:
Give it a try, and if you get stuck, post back with the code that reproduces where you got stuck.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With