Search code examples
javascriptfirebasegoogle-cloud-firestoreangularfire2

Bulk Update using Batched Write of Firebase with conditions (using WHERE function)


The main goal of my system is to update the name of the user who posted on my forum if the authenticated user change or rename his or her account name.

The whole process is error-free but unfortunately, the other user who posted in the forum also updated their name.

So this is the output:

Forum posts

I try the following:

  1. I use the WHERE function in Firebase to filter the post made by the user (log in user itself). I dont know why the whole process is failed.

This is the snippet code.

  async updateAll(username) {
    const batch = this.afs.firestore.batch();

    // cUser is the USER ID
    const userRef = this.afs
      .collection('post', (ref) => ref.where('postedById', '==', this.cUser))
      .ref.get();
    (await userRef).forEach((element) => {
      batch.update(element.ref, {
        postedBy: username,
      });
    });

    return batch.commit();
  }

Solution

  • You end your query with .ref.get(). The .ref in there, actually returns the collection on which you run the query, so you end up loading the entire post collection.

    You'll want to subscribe to snapshotChanges instead, or just use the regular JavaScript SDK to accomplish this (as you're not accessing the UI directly, I typically find that easier):

    const userRef = firebase.firestore()
      .collection('post').where('postedById', '==', this.cUser).get();
    (await userRef).forEach((element) => {
      batch.update(element.ref, {
        postedBy: username,
      });
    });