Firebase pushing array - Javascript

Viewed 28297

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);
3 Answers

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')
)

Heres an example from firebase documentation:

const admin = require('firebase-admin');
// ...
const washingtonRef = db.collection('cities').doc('DC');

// Atomically add a new region to the "regions" array field.
const unionRes = await washingtonRef.update({
  regions: admin.firestore.FieldValue.arrayUnion('greater_virginia')
});
// Atomically remove a region from the "regions" array field.
const removeRes = await washingtonRef.update({
  regions: admin.firestore.FieldValue.arrayRemove('east_coast')
});

More info on this firebase documentation.

Related