wannabefounder
wannabefounder

Reputation: 53

Query nested child sorted by date

Let's say I want to get the latest event from this Firebase data structure:

{
  events: {
    12345: {
      id: 12345,
      name: 'event1',
      date: '2016-12-30T00:00:00Z'
    },
    12346: {
      id: 12346,
      name: 'event2',
      date: '2016-12-20T00:00:00Z'
    },
    12347: {
      id: 12347,
      name: 'event3',
      date: '2016-12-10T00:00:00Z'
    }
  }
}

Is this possible or is my data structure wrong?

I've tried this without success.

firebase.database().ref('events').orderByChild('date').limitToLast(1).once('value').then((snapshot) => {
  return snapshot().val
})

Upvotes: 0

Views: 53

Answers (1)

Mathew Berg
Mathew Berg

Reputation: 28750

You shouldn't be returning it since it's done asynchronously:

firebase.database().ref('events').orderByChild('date').limitToLast(1).once('value').then((snapshot) => {
    console.log(snapshot.val());
})

Upvotes: 1

Related Questions