12

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 3

5

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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

1 Comment

Did you figure it out? Any suggestion? I am having the same issue.
0

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.

1 Comment

Your answer is based on Cloud Firestore, and the question is reference to Firebase Real Time Database. So this code won't work in RTDB.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.