DEV Community

loading...

Cannot modify a WriteBatch that has been committed

wceolin profile image Will Ceolin ・1 min read

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.

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();
});

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();
});

Discussion (1)

Collapse
soorajsnblaze333 profile image
Sooraj

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

Forem Open with the Forem app