Home > Blockchain >  Firebase Realtime database - Javascript query to retrieve values only, not including the key or &quo
Firebase Realtime database - Javascript query to retrieve values only, not including the key or &quo

Time:01-28

I am currently using firebase realtime db and writing to the db in the structure below (shown in JSON format). The first row is just for reference, second row is actual example of the data in place in this location. There are a few hundred records that are child to "push_token" in the db.

{
  "users" : {
    "push_token" : {
      "key or name" : "value",
      "-Maer1EuNpR24LdhxmIl" : "ExponentPushToken[xxxxxxxxxxxxxxxxxxxxxx]",
    }
  }
}

The below Javascript query is allowing me to get the data from the database, however, I'd like to console.log JUST the value, and not include the key or "name". That is, i'd like to only include the data to the right of the colon (the ExponentPushToken[xxxxxxxxxxxxxxxxxxxxxx]") and not the auto-assigned random key on the left.

import { getDatabase, ref, child, get } from "https://www.gstatic.com/firebasejs/9.6.4/firebase-database.js";
const db = getDatabase();
//----References----//
    var submitButton = document.getElementById("SubmitButton");

//----query database for ExpononentPushToken Values----//

  function SelectData(){
    const dbRef = ref(db);

    get(child(dbRef, `users/${"push_token"}`))
    .then((snapshot) => {
        if(snapshot.exists()) {
            console.log(snapshot.val());
        }
        else {
            console.log("No data found");
        }
    })
        .catch((error)=>{
        console.error(error);
    });
  }

//----Assign Events to Buttons----//
  submitButton.addEventListener('click', SelectData);
</script>

Is there anyway to articulate data retrieval in this manner? That is, to only get the value, apart from the key, with this db structure?

I appreciate any help I can get on this. I searched around, but could not find any simple solutions.

CodePudding user response:

To only log the values of the properties under users/push_token, you can do:

get(child(dbRef, "users/push_token"))
.then((snapshot) => {
    snapshot.forEach((child) => {
        console.log(child.val());
    })
})
.catch((error)=>{
    console.error(error);
});

The new snapshot.forEach() in here iterates over all properties under the snapshot.

  •  Tags:  
  • Related