Firebase Firestore:从文档数组追加/删除项目 [英] Firebase Firestore: Append/Remove items from document array

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

问题描述

我正在尝试从Firestore文档内的数组追加/删除项目,但每次替换整个数组而不是追加新值时,都需要这样做.我尝试了以下两种方法:

I am trying to append/remove items from an array inside of a Firestore Document but every time the entire array is replaced instead of the new value being appended. I have tried both of the following:

batch.setData(["favorites": [user.uid]], forDocument: bookRef, options: SetOptions.merge())

batch.updateData(["favorites": [user.uid]], forDocument: bookRef)

我知道我可以使用对象/字典来代替数组,但这将意味着存储无关的其他数据(例如键),我所需要的只是将ID存储在数组中.这在Firestore中是否可行?

I know that instead of an array I can use an object/dictionary but that would mean storing additional data that is irrelevant (such as the key), all I need is the ID's stored inside the array. Is this something that is currently possible in Firestore?

推荐答案

实际上,如今已经可以.最新更新db.collection.updateData 方法实际上将新项目追加到数组,而不是替换它. 用法示例可在 Firebase文档中找到.

Actually, nowadays it is possible. With latest updates db.collection.updateData method actually appends new item to array instead of replacing it. Example usage can be found in Firebase documentation.

如果您需要手动进行操作,可以使用

If you need to do it manually, you can use

FieldValue.arrayUnion([user.uid])

这篇关于Firebase Firestore:从文档数组追加/删除项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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