DEV Community

Will Ceolin
Will Ceolin

Posted on • Edited on

2 2

Cannot modify a WriteBatch that has been committed

Cloud Firestore allows batching multiple requests at once using firestore().batch(). Recently, when using it, I got the following error:

Cannot modify a WriteBatch that has been committed.
Enter fullscreen mode Exit fullscreen mode

The error is kinda self-explanatory: you're probably calling batch.update() after you've already committed your changes using batch.commit().

However, that wasn't my case. I had the following code running on Cloud Functions:

const db = admin.firestore();
const batch = db.batch();

export const myFunction = functions.firestore.document('some/doc').onChange(() => {
  const ref = db.doc('posts/123');
  batch.update(ref, {});

  return batch.commit();
});
Enter fullscreen mode Exit fullscreen mode

Did you spot my mistake in the code above? Yep, I'm calling db.batch() outside the function's scope. This means that variable was added to Cloud Function's global scope.

So, the first time that function runs, it calls batch.commit() and it commits all changes. So, when that function runs again, we get that error because commit was already called for that instance.

All we have to do to fix that bug is initializing the batch instance inside the function's scope:

const db = admin.firestore();

export const myFunction = functions.firestore.document('some/doc').onChange(() => {
  const batch = db.batch();
  const ref = db.doc('posts/123');
  batch.update(ref, {});

  return batch.commit();
});
Enter fullscreen mode Exit fullscreen mode

Follow me on Twitter

Heroku

This site is built on Heroku

Join the ranks of developers at Salesforce, Airbase, DEV, and more who deploy their mission critical applications on Heroku. Sign up today and launch your first app!

Get Started

Top comments (2)

Collapse
 
soorajsnblaze333 profile image
Sooraj (PS)

Hey Will. Really found this fix useful. Saved me a lot of time debugging :) Really appreciate it :)

Collapse
 
shrihari profile image
Shrihari Mohan

Oh man straight to the point , i was using batch on several functions so i made it outside the scope. really didn't realise on the scope level! Following you on twitter!

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay