将元素附加到 Firebase 阵列

Fed*_*oni 8 ios firebase swift firebase-realtime-database

我如何将一个元素附加到这样的数组中: 在此处输入图片说明

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

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

Dou*_*son 11

在这种情况下,您必须读取现有数据,然后将添加的新值写回。如果要执行大量追加操作,这样的数组并不总是存储数据列表的最佳方式。为此,您最好使用 childByAutoId 将数据推送到某个位置


小智 9

您可以使用此方法:firebase.firestore.FieldValue.arrayUnion()

angularfire2 示例:

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

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

  • 这是针对 firestore 而不是实时数据库 (10认同)