我一直在谷歌搜索如何将对象添加到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/