0

I have a small realtime firebase database that's set up like this:

database
-messages
--XXXXXXXXXXXX
---id : "XXX-XXX"
---content : "Hello world!"

It's a very simple message system, the id field is basically a combination of users id from my mysql database. I'm trying to return all messages that match one of the ids, either sender or receiver. But I can't do it, seems like firebase only support exacts querys. Could you give me some guidanse? Here's the code I'm working with

firebase.database().ref("messages").orderByChild("id").equalTo(userId).on("value", function(snapshot)

I'm looking for something like ".contains(userId)"

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

1 Answers1

0

Firebase supports exact matches (with equalTo) and so-called prefix queries where the value starts with a certain value (by combining startAt and endAt). It does not support querying for values that end with a certain value.

I recommend keeping a mapping from each user IDs to their messages nodes, somewhere separately in their database.

So say that you have:

messages: {
  "XXXXXXXXXXXX": {
    id : "YYY-ZZZ",
    content : "Hello world!"
  }
}

You also have the following mappings:

userMessages: {
  "YYY": {
    "XXXXXXXXXXXX": true
  },
  "ZZZ": {
    "XXXXXXXXXXXX": true
  }
}

Now with this information you can look up the messages for each user based on their ID.

For more on the modeling of this type of data, I recommend:

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