1

我一直在谷歌上搜索如何将对象添加到 firestore 中的数组中,并发现 arrayUnion() 能够将对象添加到 firestore 数组中,但它仅将对象添加到数组的最后一个索引中,但如何添加它进入数组的第一个索引?

//add "greater_virginia" into last index of array
washingtonRef.update({
    regions: firebase.firestore.FieldValue.arrayUnion("greater_virginia")
});

//how to add "greater_virginia" into first index of array?

它基本上与arrayUnion但不是将其添加到最后一个索引中,而是将其添加到数组的第一个索引中。

4

2 回答 2

2

如果 Firestore 数组的行为类似于实时数据库数组,那么它们实际上并不存在。据我所知,它们存储为地图,例如:

{
  0: "first element",
  2: "second and so on",
}

您可能会看到取消班次将是一个巨大的转变。事实上,firestore 不允许你这样做,它说“......为了避免在多用户环境中可能出现的一些问题,你将添加更多类似集合的功能” .

考虑到这一点,这个问题通常在应用程序级别通过获取数组,根据需要对其进行变异,然后设置整个事情来解决。

进一步阅读https://firebase.googleblog.com/2018/08/better-arrays-in-cloud-firestore.html

PS:小心arrayUnion操作符,因为它实际上执行了一个add to set

于 2020-04-15T04:54:47.730 回答
1

Firestore 不提供按索引修改数组字段项的任何方法。 arrayUnion如果元素尚不存在,则只会追加到数组的末尾。

如果要通过索引修改数组,则必须读取文档,修改内存中的数组以使其显示为您想要的样子,然后将修改后的数组写回文档。

于 2020-04-15T05:02:25.997 回答