Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Retrieve only specific keys from collection

Tags:

firebase

I would like to store an array of notes, where each note contains a title and a body. Is it possible to retrieve the list of note titles without the body?

For example:

notes: [
  ewi4ef36wi: {
    title: 'Shopping List',
    body: 'todo'
  }
  o9kng23inw: {
    title: 'Things To Do',
    body: ''
  }
]

How could I just retrieve the list of titles?

like image 777
Nippysaurus Avatar asked Nov 01 '14 02:11

Nippysaurus


1 Answers

Nope. Firebase's Web/JavaScript API always returns the full tree under the nodes that you request.

The most common workaround for this is that people set up a secondary branch in the tree where they just keep the keys.

Notes
    1: { "body": "hello", "title": "yessir" }
    2: { "body": "again", "title": "title2" }
    3: { "body": "there", "title": "another" }
Notes_index
    1: true
    2: true
    3: true

This is commonly referred to as an index. You'd on('child_added' on Notes_index and then (if needed) get the content of each note using once('value'.

Indexes are also often used to make nodes accessible by an alternative key. Such as a title index for the above:

Title_index
    "another": 3
    "title2": 2
    "yessir": 1

This last structure might soon not be needed anymore, since Firebase is extending their query API to allow ordering/filtering on any field. But for your use-case an index is still useful.

like image 106
Frank van Puffelen Avatar answered Oct 21 '22 04:10

Frank van Puffelen