如何从Firebase中的嵌套文档中删除数组项? [英] How to remove an array item from a nested document in firebase?

查看:53
本文介绍了如何从Firebase中的嵌套文档中删除数组项?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Vue,firebase应用程序,并将userevents保存在firebase集合中,我在用户安排事件时更新此userevents数组,并希望在用户取消或删除事件时将其删除,

I'm working on a Vue,firebase app and I'm saving the userevents in a firebase collection, I update this userevents array when a user schedule an event and want to delete it when the user cancels or remove it,

users(collection) -
 test123(document) -
      "id" . --fields
      "username" . --fields
      "userevents" . --array
         [0]
            "eventid"
            "date"
            "desc"
            "status"
         [1]
            "eventid"
            "date"
            "desc"
            "status"

从UI中,如果用户取消了一个事件,我将拥有eventid,并希望将其从userevents数组中删除. 我尝试使用下面的代码从数组中删除项目,但它正在从userevents中删除所有项目,

From UI, if the user cancels an event, I will have the eventid and want to delete it from the userevents array. I tried removing the item from the array using below code, but it is deleting all the items from the userevents,

userRef.update({
    eventid: firebase.firestore.FieldValue.delete()
});

在firebase中有没有办法做到这一点?

Is there a way to achieve this in firebase?

推荐答案

Firestore当前不支持仅使用数组中元素的字段(在您的情况下为eventid)从数组中删除元素.有两种解决方法:

Firestore currently doesn't support deleting elements from an array using just a field from an element in that array (in your case, eventid). There are a couple of workarounds:

方法1

您可以使用 FieldValue.arrayRemove 删除数组按值中的元素.该值必须与数组中的整个元素匹配,并且它将删除数组中与该值匹配的所有元素.您可以阅读有关此内容的更多信息,并在此处一般操作数组.由于您的数组元素是对象,因此代码如下所示:

You can use FieldValue.arrayRemove to remove an element from an array by value. The value has to match the whole element in the array, and it will delete all elements in the array that match that value. You can read more about that, and manipulating arrays in general here. Since your array elements are objects, the code would look like this:

userRef.update({
    "userevents": firebase.firestore.FieldValue.arrayRemove({"eventid": ..., "date": ..., "desc":..., "status":...})
});

方法2

您当前正在将对象存储在数组中.您可以做的是使userevents成为映射(对象)而不是数组.假设eventid是唯一的,您可以按eventid索引该地图,然后像这样从地图中删除该条目:

You're currently storing objects inside of an array. What you could do is make userevents a map (an object) instead of an array. Assuming that eventid is unique, you can index the map by eventid and then just delete the entry from the map like this:

userRef.update({
    ['userevents.' + eventid]: firebase.firestore.FieldValue.delete()
});

这篇关于如何从Firebase中的嵌套文档中删除数组项?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆