Firebase更新嵌套数组内的对象

问题描述 投票:2回答:1

在Firestore中,我有一个文档,该文档的属性(名称为“ items”)为数组类型。该数组包含具有以下结构的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
}  

从用户界面,用户可以更新对象的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中的更新元素flicker

javascript angular google-cloud-firestore angularfire2
1个回答
0
投票

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

© www.soinside.com 2019 - 2024. All rights reserved.