Yu Mad
Yu Mad

Reputation: 888

How to retrieve Firebase pushed key?

I have an event I'm storing in my database. It is stored as

events
   my_party123
     info
       -KZbdiR_PBrAwxYvUR4U
         name: 'John'
         city: 'Los Angeles'
   my_party124
      ...

However, I'm trying to retrieve this info and I can't quite get it.

I tried

ref
  .child('events')
  .child('my_party123') // I also tried .push('my_party123')
  .once('value')
  .then(snapshot => {
    console.log(snapshot.key) // my_party123
    console.log(snapshot.val().info) 
    // this shows object with
    // "-KZbdiR_PBrAwxYvUR4U" property, this is the pushed key property  
    im trying to access
   })

.pushed is creating new keys when i called it - how do i just access the value stored in my database?

Upvotes: 1

Views: 1206

Answers (1)

Michael Bleigh
Michael Bleigh

Reputation: 26333

If you're looking to have unique event URLs that point at events, I'd recommend a change to your data structure to be something more like:

events
  -KZ123PUSHID
    name: 'John'
    location: 'Los Angeles'
  -KZ124PUSHID
    name: 'Morgan'
    location: 'New York City'
eventNames
  my_party_123: '-KZ123PUSHID'
  sweet_nyc_part: '-KZ124PUSHID'

Then, in your code, you could do something like:

var eventNamesRef = firebase.database().ref('eventNames');
var eventsRef = firebase.database().ref('events');

var event;    
eventNamesRef.child(nameFromUrl).once('value').then(nameSnap => {
  eventsRef.child(nameSnap.val()).on('value', eventSnap => {
    event = eventSnap.val();
  });
});

Upvotes: 4

Related Questions