使用Firestore删除数组内部的对象

时间:2019-01-30 07:58:33

标签: reactjs firebase google-cloud-firestore

我想通过数组中的属性“ id”查询特定对象,然后删除/删除整个对象。通过Firestore可以做到这一点吗?

我的Firestore结构如下:

enter image description here

目前,我有一个名为removeCard()的函数,该函数接受docId(即Firestore中的文档ID)和cardId(其为对象内部的属性“ id”值)。

removeCard()函数

export const removeCard = (retroId, cardId) => {
  return (dispatch, getState, { getFirestore }) => {
    // make async call to database
    const firestore = getFirestore();

    firestore.collection('retros').doc(retroId).update({
      // firestore query to remove/delete this card.
    }).then(() => {
      dispatch({ type: 'DELETE_CARD_SUCCESS' });
    }).catch(err => {
      dispatch({ type: 'DELETE_CARD_ERROR' }, err);
    });
  }
};

但是我无法弄清楚如何执行此查询,或者是否甚至可以使用Firestore进行查询。任何帮助表示赞赏。请告诉我是否应该提供更多信息,以使我的问题更加清楚。

1 个答案:

答案 0 :(得分:1)

实际上,在编写本文时,array-contains无法查询存储在数组中的对象的特定属性。

存在一种可能的解决方法,该方法是查询整个对象

以您的情况为例

db.collection('retros').where("cardsAction", "array-contains", {id: "65....", content: "this is...", time: ....})

但是显然,这种解决方法在您的情况下将无用,因为timecontent的值可能会有所不同。

换句话说,您可能需要更改数据模型。

一种可能的方法是复制您的数据(在NoSQL世界中很常见),并在ids中仅包含cardAction的另一个数组,例如:

cardActionIds = ["65....", "5789", ....]

通过这种方式,您可以使用array-contains,一旦找到与cardActionIds相对应的文档,就可以操纵另一个数组(即cardAction