如何在Firestore中更新阵列项目 [英] How to update an array item in Firestore

查看:64
本文介绍了如何在Firestore中更新阵列项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

根据新的Firestore文档,我看到了2个新方法(arrayUnion,arrayRemove),用于处理嵌套在文档中的数组.这些方法允许您添加和删除数组项,但是如何更新现有元素?

Per the new Firestore documentation, I see 2 new methods (arrayUnion, arrayRemove) for working with arrays nested within documents. These methods allow you to add and remove an array item, but how would I update an existing element?

推荐答案

没有更新方法,因为如果要执行更新,则需要知道该特定元素的索引.在谈论Cloud Firestore阵列时,事情与您想象的不同.

There is no update method because if you want to perform an update, you need to know the index of that particular element. When talking about Cloud Firestore arrays, things are different than you might think.

由于我们正在创建可在多用户环境中使用的应用程序,因此请尝试考虑如果用户想要编辑索引0处的值,而其他用户想要删除索引0处的值可能会发生什么呢?同时其他用户可能希望在索引0处添加另一个项目.当然,您最终将获得截然不同的结果,为什么不这样做,甚至可以获得

Because we are creating apps that can be used in a multi-user environment, try to think what might happen if a user wants to edit a value at index 0, some other user wants to delete the value at index 0 and in the same time some other user might want to add another item at index 0. For sure, you'll end up having very different results and why not, get even an ArrayIndexOutOfBoundsException. So Firestore actions with arrays are a little bit different. So you cannot perform actions like, insert, update or delete at a specific index.

如Doug在他的回答中提到的那样,如果这两种方法不能为您提供足够的帮助,则应获取整个文档,获取数组,对其进行修改并将其添加回数据库中.

As Doug mentioned in his answer, if those two methods do not help you enough, you should get the entire document, get the array, modify it and add it back to the database.

这篇关于如何在Firestore中更新阵列项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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