Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Append element to Firebase Array

How I could append an element to an array like that: enter image description here

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
like image 934
Federico Malagoni Avatar asked Mar 09 '18 15:03

Federico Malagoni


Video Answer


3 Answers

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.

like image 26
Doug Stevenson Avatar answered Oct 11 '22 23:10

Doug Stevenson


You could use this method: firebase.firestore.FieldValue.arrayUnion()

Example with angularfire2:

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

For more information: https://firebase.google.com/docs/reference/js/firebase.firestore.FieldValue#arrayunion

like image 145
Sebastián de Prada Gato Avatar answered Oct 11 '22 23:10

Sebastián de Prada Gato


You could set the values of the keys in the array to true, and then set the value directly in an update.

So if 'newId' is the new item to add, maybe something like:

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

Firebase docs example of an update: https://firebase.google.com/docs/database/web/read-and-write

like image 34
ludichrislyts Avatar answered Oct 11 '22 22:10

ludichrislyts