[英]Firebase database. How to append values to array?
I have the following test data我有以下测试数据
1: {
match: "Game 1",
scorer: ["foo","bar"] //this could also be an object
}
My question is how do I correctly append new value to an array without overwriting it?我的问题是如何正确地将 append 新值赋给数组而不覆盖它? My idea was to retrieve existing data then spread it like so [...currentData, "bob"]
.我的想法是检索现有数据,然后像这样传播它[...currentData, "bob"]
。 Is there a better alternative?有更好的选择吗?
const addScorer = (matchId) => {
return update(ref(db, path), {
scorer: ["bob"]
})
}
There is no atomic operation to add an item to an array directly in the database.没有直接在数据库中将项目添加到数组的原子操作。 This means you'll need to:这意味着您需要:
This is one of the many reasons why Firebase recommends against using arrays for lists of data, but instead has a push()
operation that circumvents most problems.这是 Firebase 建议不要将 arrays 用于数据列表的众多原因之一,而是使用push()
操作来规避大多数问题。 For more on this, see the link to the document that Nilesh included in their comment, or read this article on Best Practices: Arrays in Firebase .有关这方面的更多信息,请参阅 Nilesh 在其评论中包含的文档链接,或阅读有关最佳实践的这篇文章:Firebase 中的 Arrays 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.