簡體   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