Mike Miller
Mike Miller

Reputation: 3507

Search by key, order by value

Here is a sample of my Firebase data:

data

I need to be able to search userFavorites for a given user (here, afaapy...) and return the results ordered by the values (timestamps) to get all the user's favorites in order of the date added to the database.

I can search by key as follows, and retrieve all favorites for the given user:

databaseRef.child("userFavorites").queryOrderedByKey().queryEqual(toValue: user.uid).observe(...)

But these favorties are ordered by their keys. If I try to order by value as follows, I get "Cannot use multiple queryOrderedBy calls!":

databaseRef.child("userFavorites").queryOrderedByKey().queryEqual(toValue: user.uid).queryOrderedByValue().observe(...)

How can I retrieve the favorites for a given user sorted by their value?

Second question: is there an easier way to retrieve data in the order it was added to the database?

Upvotes: 0

Views: 7203

Answers (1)

SylvainC
SylvainC

Reputation: 104

You can't order the same ref multiple times as documented here

When you use a order or a filter method, it returns a Query Interface. See it as a filtered reference containing only a subset of the original data. It means that

databaseRef.child("userFavorites").orderByKey().equalTo(user.uid)

will not return userFavorite/${user.uid} but userFavorite filtered to show only the user.uid entry. You can see it by doing

databaseRef.child("userFavorites").orderByKey().equalTo(user.uid).ref.key

That should return 'userFavorites'

In your case, I see two options:

Keep going with orderByKey().equalTo() and sort the results yourself

Or use directly child() to get the user, then sort via Firebase (and don't forget to use the Firebase's snapshot.forEach to be sure you get the data in the query order):

databaseRef.child(`userFavorites/${user.uid}`).orderByValue().once('value', (snapshot) => {
      if (snapshot.exists()) {
        snapshot.forEach((child) => {
          console.log(`${child.key}: ${child.val()}`)
        })
      }
    })

Upvotes: 4

Related Questions