Search code examples
angulartypescriptangularfire

Cannot read propery afs (Angularfirestore) of undefined on collection.set()


I use the following code, to iterate over a collection of data, and change a field if the email matches. Note that the code crashes on the set. The iteration works just fine. afs is initialized as AngularFirestore

onChangeRole(email) {
  this.afs.collection("users").get().toPromise().then(function (querySnapshot) {
    querySnapshot.forEach(function (doc) {
      // doc.data() is never undefined for query doc snapshots
      console.log(doc.id, " => ", doc.data());

      if (doc.data().email == email) {
        this.afs.collection("users").doc(doc.id).set({
          role: 2
        })
      }
    });
  });
}

But im receiving:

ERROR Error: Uncaught (in promise): TypeError: Cannot read property 'afs' of undefined TypeError: Cannot read property 'afs' of undefined

Where afs is AngularFirestore

import { AngularFirestore, AngularFirestoreCollection , AngularFirestoreDocument} from '@angular/fire/firestore';

Solution

  • This should work

    onChangeRole(email) {
      const usersColl = this.afs.collection("users");
      usersColl.get().toPromise().then(function (querySnapshot) {
        querySnapshot.forEach(function (doc) {
          console.log(doc.id, " => ", doc.data());
          if (doc.data().email == email) {
            usersColl.doc(doc.id).set(
              { role: 2 },
              { merge: true }
            )
          }
        });
      });
    }