【问题标题】:Append element to Firebase Array将元素附加到 Firebase 数组
【发布时间】:2018-08-18 05:10:01
【问题描述】:

如何将元素附加到这样的数组:

使用此代码,我将覆盖旧数据:

let toUpdate = [book.id]
self.refUsers.child(localUser.key!).child("booksPurchased").setValue(toUpdate, withCompletionBlock: { (error, _) in

【问题讨论】:

  • 每次在同时修改的数据中使用数组时,一只小狗就会死去。

标签: ios swift firebase firebase-realtime-database


【解决方案1】:

在这种情况下,您必须读取现有数据,然后将其写回并添加新值。如果您想要执行大量附加操作,这样的数组并不总是存储数据列表的最佳方式。为此,你最好pushing data into a location using childByAutoId

【讨论】:

    【解决方案2】:

    你可以使用这个方法:firebase.firestore.FieldValue.arrayUnion()

    angularfire2 示例:

    this.afs.collection('collection').doc(id).update( {
       array: firebase.firestore.FieldValue.arrayUnion( 'newItem' )
    });
    

    欲了解更多信息:https://firebase.google.com/docs/reference/js/firebase.firestore.FieldValue#arrayunion

    【讨论】:

    • 那是用于firestore而不是实时数据库
    【解决方案3】:

    您可以将数组中键的值设置为true,然后直接在更新中设置该值。

    因此,如果“newId”是要添加的新项目,可能类似于:

    const update = {
       [`/users/${localUser.key}/booksPurchased/${newId}`]: true]
    }
    firebase.db.ref().udpate(update);
    

    Firebase 文档更新示例: https://firebase.google.com/docs/database/web/read-and-write

    【讨论】:

    • 这对我有帮助,但问题是关于 iOS 的,我认为您发布了网络解决方案。
    • 但结果不会是数组,使用 childByAutoId 比使用 boolean 更好。
    【解决方案4】:

    读写列表 追加到数据列表

    使用 childByAutoId 方法将数据附加到多用户应用程序中的列表。每次将新子项添加到指定的 Firebase 引用时,childByAutoId 方法都会生成一个唯一键。通过为列表中的每个新元素使用这些自动生成的键,多个客户端可以同时将子元素添加到同一位置,而不会发生写入冲突。 childByAutoId 生成的唯一键是基于时间戳的,因此列表项会自动按时间顺序排列。

    您可以使用对childByAutoId方法返回的新数据的引用来获取孩子的自动生成的key的值或为孩子设置数据。对 childByAutoId 引用调用 getKey 会返回自动生成的密钥。

    您可以使用这些自动生成的键来简化数据结构的扁平化。有关详细信息,请参阅数据扇出示例。

    -https://firebase.google.com/docs/database/ios/lists-of-data

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-07-04
      • 2014-02-24
      • 1970-01-01
      • 2020-07-07
      • 2016-12-22
      • 1970-01-01
      • 1970-01-01
      • 2014-11-15
      相关资源
      最近更新 更多