2

I would like to get data from my firebase realtime database, but I only want to get the data that includes the current users UID.

See the image for the database structure:

picture of the db, explains the problem

I don't get the hang of firebase querying/sorting from the docs: https://firebase.google.com/docs/database/web/lists-of-data

// Gets all chats
return firebase.database().ref(`chat`);

// would like to do something like this 
let userId = firebase.auth().currentUser.uid
firebase.database().ref('/chat/' + userId).once('value')

Would appreciate any help or tips for solving this.

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
charles
  • 73
  • 3
  • 12

1 Answers1

0

There is no way to directly query the chats based on the UID, since the keys end with the UID and don't start with them. This is expected behavior, I would consider it a code smell if you parsed keys in the way you seem to be trying.

Instead, keep a list of the chat IDs for each user.

userChats
  uid1
    chatid1: true
    chatid2: true
  uid2
    chatid2: true

This way you can load the chat IDs for a user from /users/$uid and then load each individual chat. The latter is not nearly as slow as some developers think it is, because Firebase pipelines these requests over a single connection. See http://stackoverflow.com/questions/35931526/speed-up-fetching-posts-for-my-social-network-app-by-using-query-instead-of-obse/35932786#35932786

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807