首页 > 解决方案 > 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 中闪烁。

标签: javascriptangulargoogle-cloud-firestoreangularfire2

解决方案


尽管如此,仍然无法更新对象数组的特定字段。(arrayRemove/arrayUnion) 是唯一的解决方案。


推荐阅读