Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Firebase pushing array - Javascript

I am using Firebase to store information for a workout application.

I user adds a workout name and then I push it to the database. I can continue pushing these but my issue is that it does not seem to be pushing as an array just an object. See the screen shots below...

Console log from firebase object

enter image description here

As you can see in the console log picture the workouts property is an object not an array like I expect.

The code I'm using to push it:

    let newWorkout = {
      title: 'title',
      exercises: [{
        name: 'pulldownsnsn',
        sets: 4
      }]}

    let ref = firebase.database().ref("/userProfile/"+this.userId);

    ref.child("workouts").push(newWorkout);
like image 416
okayilltry Avatar asked May 30 '17 13:05

okayilltry


2 Answers

The Firebase Database stores lists of data in a different format, to cater for the multi-user and offline aspects of modern web. The -K... are called push IDs and are the expected behavior when you call push() on a database reference.

See this blog post on how Firebase handles arrays, this blog post on the format of those keys, and the Firebase documentation on adding data to lists.

like image 160
Frank van Puffelen Avatar answered Nov 14 '22 16:11

Frank van Puffelen


Arrays are handy, but they are a distributed database nightmare for one simple reason: index element identification is not reliable when elements get pushed or deleted. Firebase database instead uses keys for element identification:

// javascript object
['hello', 'world']

// database object
{ -PKQdFz22Yu: 'hello', -VxzzHd1Umr: 'world' }

It gets tricky when using push(), because it does not actually behaves like a normal push, but rather as a key generation followed by object modification.

Example usage

firebase.database().ref('/uri/to/list').push(
    newElement,
    err => console.log(err ? 'error while pushing' : 'successful push')
)
like image 22
Nino Filiu Avatar answered Nov 14 '22 15:11

Nino Filiu