1

I would like to give multiple users access to fetch "messages" they have access to in a Firebase Realtime database. The database fetch reads "/messages" and returns two collections of all messages the user has access as "author" and "member".

Database structure looks like this:

"messages" : {
  "msg_id1": {
    "access": {
      "author": "user-id-1",
      "members": {
        "user-id-2": true
      }
    }
    "data" : {
      "theData": "Hello world!"
    }
  }
}

I have created the following rule:

{
  "rules": {
    "messages": {
      ".read": "
        auth.uid !== null &&
        query.equalTo === auth.uid
      "
    }
}

The corresponding database queries are:

database.ref("messages")
  .orderByChild("access/author")
  .equalTo(`${user.uid}`)
  .once('value', (snapshot) => {
    snapshot.forEach( (data) => {
      console.log("OWNER", data.val().data.title)
    })
})

database.ref("messages")
  .orderByChild(`access/members/${user.uid}`)
  .equalTo(true)
  .once('value', (snapshot) => {
    snapshot.forEach( (data) => {
      console.log("MEMBER", data.val().message.data.title)
    })
})

I wish to minimise the overhead and cost of calling the database twice.

Is there a smart way to optimise the database queries into one single database call?

Kind regards /K

Kermit
  • 2,865
  • 3
  • 30
  • 53
  • 1
    You will have to duplicate the data into another location in the database that is organized in such a way that you can get everything you need with a single query. This is actually kind of common with NoSQL type databases. – Doug Stevenson Aug 04 '19 at 19:57
  • 1
    Note that the number of calls to the database is usually only a small factor in the performance, as Firebase can pipeline most requests over its existing connection. See https://stackoverflow.com/questions/35931526/speed-up-fetching-posts-for-my-social-network-app-by-using-query-instead-of-obse/35932786#35932786 – Frank van Puffelen Aug 04 '19 at 23:12
  • Thank you @DougStevenson - Can you please link me to more information on best practices for this type of data organisation? – Kermit Aug 07 '19 at 06:35

0 Answers0