简体   繁体   English

Firebase 数据库。 如何将 append 个值转入数组?

[英]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:这意味着您需要:

  1. Read the array into your application code将数组读入您的应用程序代码
  2. Append the item to the array Append 项目到数组
  3. Write the entire array back to the database将整个数组写回数据库

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.

相关问题 Firebase V9 数据库。 批处理操作? - Firebase V9 Database. Batching operations? 如何删除创建的 firestore 数据库。? - How to delete a created firestore database.? 如何使用 arrayUnion (TypeScript) 将字符串数组 append 转换为 Firebase 中的数组 - How to append an array of strings to an array in Firebase using arrayUnion (TypeScript) 关于firebase实时数据库的基本问题。 是否有从 UI 隐藏实现的好模式? - Basic question about firebase real time database. Is there a good pattern for hiding the implementations from the UI? 如何有效地从 Firebase 数据库中获取数组? - How to get an array from Firebase database efficiently? Firebase 数据库未填充值 - Firebase database not filling with values 不能append数据从Firebase到数组SwiftUI - Cannot append data from Firebase to Array SwiftUI 我的应用程序返回到上一页而没有将数据更新到数据库。 (使用 Android studio + Firebase) - My app is gets back to previous page without updating data to database. (Using Android studio + Firebase) 如何在不转换为数组的情况下将数字添加为 firebase 实时数据库子项? - How to add number as firebase realtime database child without converting to array? 我如何在 firebase 数据库中使用相同的键来总结值 - How do i sum up values with the same key in firebase database
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM