将元素追加到Firebase数组

问题描述:

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

How I could append an element to an array like that:

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

Using this code I'm overriding the old data:

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

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

In this case, you will have to read the existing data, then write it back with the new value added. Arrays like this are not always the best way to store lists of data if you want to perform a lot of append operations. For that, you're better off pushing data into a location using childByAutoId.