angular - 如何添加到 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 方法从数组中删除。
解决方案
不需要云函数,使用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
推荐阅读
- angular-forms - 如何使用 Angular 8 创建可重用的复选框组件?
- typescript - Phaser 3 typescript player.alive 未定义
- google-cloud-storage - GCS 存储创建文件夹 API
- android-studio - 来自 git 的一些旧项目的问题同步 gradle
- java - sftp二次开发如何使用guacamole
- python - 比较两个不同数据框的两列并使用 If 条件创建新列
- jquery - .Closest() with Classes 似乎没有选择正确的元素
- android - 在 iOS 的 UITextView 上加载 html 字体的问题
- android - 如何使用 TypeConverter 将 Joda-Time Period 字段保存到 Room 中?
- regex - Python中以下特定情况下正则表达式与字符串操作的性能比较