如何从Firestore中的数组删除对象

Luk*_*kas 4 javascript firebase google-cloud-firestore

我有删除的问题Object出的Arrayfirestore。我在Firestore中有以下数据:

在此处输入图片说明 在此处输入图片说明

现在我想删除例如第二个 Object出来的posts Array

码:

 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);
  });
}
Run Code Online (Sandbox Code Playgroud)

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

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

在此处输入图片说明

Evi*_*n1_ 41

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

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

Run Code Online (Sandbox Code Playgroud)

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

  • 这仅适用于简单数组,如 ["test","test2"] ,如果你有对象数组 [{},{},{}] (11认同)

Ido*_*ev 15

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

例如:

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

const obj = { field1, field2 ... } 

collectionRef.doc(docId).update({
    myArray: firebase.firestore.FieldValue.arrayRemove(obj)
})
Run Code Online (Sandbox Code Playgroud)


Fab*_*ard 6

不能使用滤镜吗?然后将新的posts数组返回到您的fb.usersCollection方法

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

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

 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);
  });
}
Run Code Online (Sandbox Code Playgroud)

  • 如果您正在处理大量数据,您将把所有元素下载到您的应用程序中,只是为了删除一个元素。它没有优化。 (2认同)