繁体   English   中英

如何从 firestore 中的数组中删除 object

[英]How to delete object from array in firestore

我在从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()

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

在此处输入图像描述

您还可以使用FieldValue助手中的arrayRemove方法。

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

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

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

你不能用过滤器吗? 然后将新的帖子数组返回到您的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);
  });
}

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

例如:

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

const obj = { field1, field2 ... } 

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

更新数组中的元素

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

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

如果您使用的是Firebase V9 (modular) ,您可以像这样简单地从Firestore导入arrayRemove

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM