1

I have a realtime database structure like below. Users have some friends. For example, I am Joe and I'd like to fetch users who have friends as Joe.

In this example, Dave and Harry have a friend called Joe, so my query should fetch Dave and Harry but shouldn't Micheal.

Is there a way to do this without fetching data in a loop?

{
"Users": {
    "Joe": {
        "Friends": ["Dave","Harry","Micheal"]
    },
    "Dave": {
        "Friends": ["Joe","Jack","Brent"]
    },
    "Harry": {
        "Friends": ["Jack","Joe"]
    },
    "Micheal": {
        "Friends": ["Ken","Jack","Brent"]
    }
}

}

2
  • Are you asking about Realtime Database or Firestore? Commented Mar 13, 2018 at 12:56
  • Realtime database Commented Mar 13, 2018 at 12:56

1 Answer 1

1

Firebase Realtime database cannot perform a query across array members, to see if it contains a specific value in any position or to add/remove a record. Firebase documentation recommends against using arrays. One of the many reasons Firebase recommends against using arrays is that it makes the security rules impossible to write.

As usual with NoSQL databases: if you can't perform the use-case you want with your current data structure, you can typically change/expand your data structure to allow the use-case. The best practice is to use maps instead of arrays. A possible database structure could look like this:

"Users": {
    "Joe": {
        "Friends"
            "Dave": true,
            "Harry": true,
            "Micheal": true
    },
    "Dave": {
        "Friends"
            "Joe": true,
            "Jack":true,
            "Brent": true

    },
    "Harry": {
        "Friends"
            "Jack": true,
            "Joe": true
    },
    "Micheal": {
        "Friends"
            "Ken":true,
            "Jack": true,
            "Brent": true
    }
}

You can also take a look, here, for more informations.

Sign up to request clarification or add additional context in comments.

2 Comments

Is there everything alright? Have you solved the issue?
Your answer Alex was usefull to me anyway.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.