如何从Firestore数组中删除对象

30

我在firestore中删除一个Array中的一个Object遇到了问题。

我在firestore中有以下数据:

enter image description here enter image description here

现在,我想删除例如posts数组中的第二个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()

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

图片描述


请参见以下链接:https://dev59.com/JK7la4cB1Zd3GeqPXh_u - rolznz
5个回答

56

30
只有当数组是简单的 ["test", "test2"] 时,这个方法才有效,如果你有对象数组 [{}, {}, {}],则不适用。 - Patrik Spišák
@PatrikSpišák 在保存数组之前,将其转换为映射表。 - Walter Monecke

21

编辑:警告 不要使用我的解决方案,因为它已经超过3年了,现在有新的解决方案:https://dev59.com/8VQK5IYBdhLWcg3wQdzI#59745086 我的方案是一个纯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() 呢? - Lukas
这将存储一个新的数组,不包括您删除的帖子,因此这是您的 delete() 方法。 - Fabien Greard
我更新了我的回答,然后你必须从用户点击删除按钮获取deleteId。 - Fabien Greard
deleteId是您通过函数传递的参数,当用户单击按钮时,您希望获取帖子的ID或任何其他信息,以便找到要删除的帖子。 - Fabien Greard
2
如果你正在处理大量数据,你会下载所有元素到你的应用程序中,只为了删除一个。这并不是最优化的做法。 - BorisD
显示剩余3条评论

14

您可以使用 arrayRemove 函数来删除数组中的对象。

但是,您需要提供一个对象。该对象需要与您在 Firestore 集合中的文档数组中的对象完全相同。

例如:

以下代码将从 myArray 数组中删除 obj,但仅当 obj 正好存在于该数组中时才会进行删除。

const obj = { field1, field2 ... } 

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

3

更新数组元素

如果你的文档包含一个数组字段,你可以使用 arrayUnion() 和 arrayRemove() 来添加和删除元素。arrayUnion() 添加元素到数组中但只添加那些不存在的元素。arrayRemove() 则移除所有给定元素的实例。

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

0

如果您正在使用Firebase V9 (modular),您可以像这样从Firestore导入arrayRemove

import { doc, updateDoc, arrayRemove } from 'firebase/firestore';

const docRef = doc(db, 'collection', 'doc');
await updateDoc(docRef, {
  arrayName: arrayRemove('elementName');
}); 

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接