I'm trying to create a save transaction with Flutter / Dart and Firestore which does the following:
- Add a new item with attribute "position: 1" to a collection of documents
- Increment the "position" attributes of all other documents in this collection with a position > 1 by 1 (++)
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());
});
}