【问题标题】:How to delete object from array in firestore如何从firestore中的数组中删除对象
【发布时间】:2019-02-08 13:09:36
【问题描述】:

我在从firestore 中的Array 中删除Object 时遇到问题。 我在 Firestore 中有这些数据:

现在我想从posts Array 中删除例如第二个Object

代码:

 deletePic () {
  let docId = `${this.currentUser.uid}`

   fb.usersCollection.doc(docId).update({
     posts: firebase.firestore.FieldValue.arrayRemove()
   })
  .catch(function(error) {
      console.error("Error removing document: ", error);
  });
}

但我不知道如何定义arrayRemove()

这些是图片,每张都有一个删除按钮来删除图片。

【问题讨论】:

标签: javascript firebase google-cloud-firestore


【解决方案1】:

您还可以使用 FieldValue 帮助程序中的 arrayRemove 方法。

docRef.update({
   array: FieldValue.arrayRemove('idToRemove');
});

https://firebase.googleblog.com/2018/08/better-arrays-in-cloud-firestore.html

【讨论】:

  • 这个仅适用于简单的数组,例如 ["test","test2"] 如果你有对象数组 [{},{},{}]
  • @PatrikSpišák 之前不是保存数组而是转换为地图。
【解决方案2】:

编辑:警告不要使用我的解决方案,因为它已经超过 3 年了,现在有新的解决方案:https://stackoverflow.com/a/59745086/6668441 我的解决方案是纯 js 的,是一个糟糕的模式。

你不能使用filter 吗?然后将新的帖子数组返回到您的fb.usersCollection 方法

//deleteId is the id from the post you want to delete
posts.filter(post => post.id !== deleteId);

编辑:所以这应该是这样的:

 deletePic (deleteId) {
  let docId = `${this.currentUser.uid}`

   //deleteId is the id from the post you want to delete

   fb.usersCollection.doc(docId).update({
     posts: posts.filter(post => post.id !== deleteId);
   })
  .catch(function(error) {
      console.error("Error removing document: ", error);
  });
}

【讨论】:

  • 在哪里设置 delete() 或 arrayRemove()?
  • 这将存储一个没有您删除的帖子的新数组,所以这是您的 delete() 方法
  • 我更新了我的答案,那么你必须从用户点击删除按钮获取deleteId
  • deleteId 应该包含在对象内还是?
  • 如果您正在处理大量数据,您会将所有元素下载到您的应用程序中,以便删除一个。它没有优化。
【解决方案3】:

您可以使用arrayRemove 函数删除数组中的对象。 但是,您需要提供一个对象。 该对象需要与 firestore 集合中 doc 数组中的对象相同。

例如:

以下代码将从myArray数组中删除obj, 但前提是 obj 完全存在于该数组中。

const obj = { field1, field2 ... } 

collectionRef.doc(docId).update({
    myArray: firebase.firestore.FieldValue.arrayRemove(obj)
})

【讨论】:

    【解决方案4】:

    Update elements in an array

    如果您的文档包含数组字段,则可以使用 arrayUnion() 和 arrayRemove() 添加和删除元素。 arrayUnion() 添加元素 到一个数组,但只有尚未存在的元素。数组删除() 删除每个给定元素的所有实例。

    // Atomically remove a region from the 'regions' array field.
    city_ref.update({u'regions': firestore.ArrayRemove([u'east_coast'])})
    

    【讨论】:

      【解决方案5】:

      如果您使用的是Firebase V9 (modular),您可以简单地从Firestore 导入arrayRemove,如下所示:

      import { doc, updateDoc, arrayRemove } from 'firebase/firestore';
      
      const docRef = doc(db, 'collection', 'doc');
      await updateDoc(docRef, {
        arrayName: arrayRemove('elementName');
      }); 
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2023-02-08
        • 1970-01-01
        • 2023-01-16
        • 2017-06-15
        • 1970-01-01
        • 1970-01-01
        • 2023-01-30
        相关资源
        最近更新 更多