首页 > 解决方案 > 如何添加到 Angular Firestore 中的数组?

问题描述

我正在尝试使用 Angular Fire 2 将 ID 添加到我的用户集合中,以便在 Firestore 中进行访问控制。

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

当前授予方法正在替换数组中的 id。如果值不存在({merge: true} 不起作用),我如何添加到数组并使用 remove 方法从数组中删除。

标签: angularfirebasegoogle-cloud-firestoreangularfire2

解决方案


不需要云函数,使用arrayUnion:

var washingtonRef = db.collection("cities").doc("DC");

// Atomically add a new region to the "regions" array field.
washingtonRef.update({
    regions: firebase.firestore.FieldValue.arrayUnion("greater_virginia")
});

// Atomically remove a region from the "regions" array field.
washingtonRef.update({
    regions: firebase.firestore.FieldValue.arrayRemove("east_coast")
});

以上来自Pepe链接的文档:https ://firebase.google.com/docs/firestore/manage-data/add-data#web-v8_11


推荐阅读