javascript - 如何将对象添加到firestore对象数组的第一个索引

标签 javascript arrays reactjs react-native google-cloud-firestore

我一直在谷歌搜索如何将对象添加到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基本相同,但我不想将其添加到最后一个索引中,而是想将其添加到数组的第一个索引中。

最佳答案

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

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

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

考虑到这一点,这个问题通常在应用程序级别解决,方法是获取数组,根据需要改变它,然后设置整个事情。

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

PS:请小心使用 arrayUnion 运算符,因为它实际上执行add to set

关于javascript - 如何将对象添加到firestore对象数组的第一个索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61221389/

相关文章:

php - "Notice: Undefined variable"、 "Notice: Undefined index"、 "Warning: Undefined array key"和 "Notice: Undefined offset"使用 PHP

php - 在 PHP 中循环遍历这个数组的最佳方法是什么?

javascript - 如何从 API 调用中获取响应 JSON

for循环中的javascript闭包不起作用

javascript - 我的 JavaScript 没有在 CodePen 中运行,我不知道这是否是我的代码的错误

javascript - HTML 自动在 Opening-Table 中突出显示当天

c#悖论: Converting List to Array is Iterating more efficient?

javascript - 为什么有人想在 React js 中将一个函数变成一个类

javascript - 如何使用 React es6 处理多个受控输入?

javascript - 使用 jQuery 创建一个数组而不是从 dom 中获取的值的变量?