How to query Firebase data after using .push() to add data?

2k Views Asked by At

Here is the code for when I'm pushing the data to Firebase:

firebase.database().ref(`booklogs/${uid}/${book_id}`).push(page_id)

booklogs : 
{HUMjSHxVKAPfVXzOId9zCBkGOgv1:{
 book28917: {
 -KYp4FdYYODDZG1FX-Pb: 1
}
}
}

My problem is when I query the data, the child node of the ${book_id} includes the push key, but I only want to get the value which is 1 and not the push key.

The code I use to query is:

var booklogs = db.ref(`booklogs/${uid}/${project}`); 

booklogs.once('value')
  .then((snapshot) => {
    console.log(`pages viewed are  ${snapshot.key}: ${snapshot.val()}`);
    console.dir(snapshot.val());
  }).catch((error) => {
    console.log(`Error : ${error}`);
  });

The data returned in the console is:

pages viewed are  2634651: [object Object]                                                                            
{ '-KYp4FdYYODDZG1FX-Pb': 1 } 

Any input would be much appreciated. Thanks!

1

There are 1 best solutions below

5
On

If you only want the '1' and not the push key, try using .set()

firebase.database().ref(`booklogs/${uid}/${book_id}`).set(page_id)

That will get rid of the object and just give you the value that you wanted. Push automatically generates a key for every value you add, so you will always get an object back. From the Firebase docs - "For basic write operations, you can use set() to save data to a specified reference, replacing any existing data at that path."

https://firebase.google.com/docs/database/web/read-and-write