Search code examples
angularfirebasegoogle-cloud-firestoreangularfire2

How do I add to an array in Angular Firestore?


Im trying to add ids to my user collection for Access Control in Firestore using Angular Fire 2.

 grantCompanyAccess (user, companyId) {
    try {
      const userAccess: AngularFirestoreDocument<any> = this.afs.doc(`users/${user.uid}`);
      return userAccess.set({companies: [companyId]});
    } catch (error) {
      console.log(error);
    }
  }

  removeCompanyAccess (user, companyId) {
    try {
      const userAccess: AngularFirestoreDocument<any> = this.afs.doc(`users/${user.uid}`);
      const userData = {
        companies:  [{companyId}]
      };
      // return userAccess.collection('companies').doc(companyId).delete();
      return userAccess.collection('companies').doc(companyId).delete();
    } catch (error) {
      console.log(error);
    }
  }

Currently grant method is replacing the id in the array. How do I add to the array if the value does not exist ({merge: true} does not work) and delete from the array using the remove method.


Solution

  • You should first get the array from firebase and then push your new id into that array. After that you can set companies with the updated array.