javascript - Firebase 更新嵌套数组中的对象
问题描述
在 Firestore 中,我有一个具有数组类型属性(名为“项目”)的文档。该数组包含ShoppingItem
具有以下结构的对象:
export class ShoppingItem {
id?: string;
name: string;
checked = false;
}
为了完整起见,在文档结构下方:
export interface ShoppingList {
id: string;
name?: string;
items: ShoppingItem[]; // <-- This is the array property I am updating
}
从 UI 中,用户可以更新checked
对象的属性,我想相应地更新数据库。我从 Firebase 文档中读到,我们可以使用它arrayRemove/arrayUnion
来原子地删除/添加数组项。
为了更新现有项目,我是否必须删除旧对象并每次都添加新对象(嵌套承诺),如下所示?还是有可能以更优雅的方式?
updateItem(listId: string, item: ShoppingItem) {
const docRef = this.db.collection("list").doc(listId)
return docref.update({ items: firestore.FieldValue.arrayRemove(item) })
.then(() => {
{
docRef.update({ items: firestore.FieldValue.arrayUnion(item) });
}
});
}
在数组中删除和添加项目的另一个缺点是更新的元素在 UI 中闪烁。
解决方案
尽管如此,仍然无法更新对象数组的特定字段。(arrayRemove/arrayUnion) 是唯一的解决方案。
推荐阅读
- javascript - axios请求检索数据后如何使用V-For?
- java - 如何在spring中创建已经代理的类的动态代理
- c++ - 为什么 C++ 哈希函数的返回类型是 std::size_t,而不是与平台无关的类型?
- c# - 以随机方式分配任务的算法,几乎没有偏差
- r - 物料需求计划包
- python - 使用自定义变压器时如何正确腌制sklearn管道
- python - 如何在删除网格线后将图表边框角更改为圆形并更改 Excel 工作表背景的颜色
- uibutton - UIButton width doesn't increase based on text if insets are given
- laravel - Laravel 6.0 app.js 只有 require('.bootstrap');?
- spring - 在 SpringBoot 控制器中接收/发送 MultiRow 数据以及文件