Firebase 更新嵌套数组内的对象

Fra*_*sco 5 javascript angularfire2 angular google-cloud-firestore

在 Firestore 中,我有一个具有数组类型属性(名为“items”)的文档。该数组包含ShoppingItem具有以下结构的对象:

export class ShoppingItem {
 id?: string; 
 name: string;
 checked = false;
}
Run Code Online (Sandbox Code Playgroud)

为了完成起见,在文档结构下方:

export interface ShoppingList {
 id: string;
 name?: string;
 items: ShoppingItem[]; // <-- This is the array property I am updating
}  
Run Code Online (Sandbox Code Playgroud)

从用户界面,用户可以更新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) });
    }
  });
}
Run Code Online (Sandbox Code Playgroud)

在数组中删除和添加项目的另一个缺点是更新的元素在 UI 中闪烁

小智 1

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