Cannot modify a WriteBatch that has been committed

Will Ceolin - Jul 31 '20 - - Dev Community

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

. . . . . . . . . . . . . . . . . . . . . . . . .
Terabox Video Player