iDecode
iDecode

Reputation: 28886

How to run transaction in cloud_firestore_odm?

I want to run a transaction to update data in the Cloud Firestore using cloud_firestore_odm.

This code works fine:

usersRef 
  .doc('foo_id')
  .update(
    name: 'John',
  );

But this one doesn't. I'm doing something wrong, can anyone tell me how to properly do it?

final transaction = await FirebaseFirestore.instance.runTransaction((_) async => _);

usersRef 
  .doc('foo_id')
  .transactionUpdate(
    transaction,
    name: 'John',
  );

Upvotes: 3

Views: 423

Answers (2)

Rémi Rousselet
Rémi Rousselet

Reputation: 276941

Due to how the ODM works, the syntax for using transactions using the Firestore ODM is slightly different.

Instead of:

await FirebaseFirestore.instance.runTransaction((transaction) async {
  transaction.update(usersRef.doc('id'), {'age': 42});  
});

You should do:

await FirebaseFirestore.instance.runTransaction((transaction) async {
  usersRef.doc('id').transactionUpdate(transaction, age: 42);  
});

Basically, the transaction vs "reference" are swapped. But as a benefit, the transaction object is fully typed.

The same logic applies for any other transaction method.

Upvotes: 4

Josteve Adekanbi
Josteve Adekanbi

Reputation: 12673

Try this:

await FirebaseFirestore.instance((transaction) async {
   await transaction.update(usersRef.doc('foo_id'),{
     'name' : 'John'
   });
});

Upvotes: 0

Related Questions