Joao Belem Jr.
Joao Belem Jr.

Reputation: 121

Firebase: Querying data inside an unknown name key (child inside another child)

I'm developing a React Native app and having a query doubts.

I need to return all groups (eg "group-id-01"), where the provided UID exists within members.

Firebase

This code return all groups:

const memberGroup = firebase.database().ref('groups')
memberGroup.once('value')
        .then((snapshot) => {
          console.log('snapshot');
          console.log(snapshot.val());
        })
        .catch((error) => {
          console.log('Erro');
          console.log(error);
        });

Result I'm having:

"group-id-01"
  "members"
    "no-uid-provided":"Belem"
    "oZlTzlbCTGaZfsrzyxqABlnxt2e2":"Julia"
  "name":"Rolling Stones"

Result I want:

"group-id-01"
  "members"
    "oZlTzlbCTGaZfsrzyxqABlnxt2e2":"Julia"
  "name":"Rolling Stones"

Whell...

I've tried some queries with .orderByChild and .equalTo, but the result is null.

const memberGroup = firebase.database().ref('groups')
.orderByChild('oZlTzlbCTGaZfsrzyxqABlnxt2e2')
.equalTo('Julia')

memberGroup.once('value')
        .then((snapshot) => {
          console.log('snapshot');
          console.log(snapshot.val());
        })
        .catch((error) => {
          console.log('Erro');
          console.log(error);
        });

I'm new in Firebase and I don't know if is possible to query a child inside another child with unknown name.

Appreciate all the help :D

Upvotes: 1

Views: 596

Answers (1)

Frank van Puffelen
Frank van Puffelen

Reputation: 598740

Your current structure allows you to easily look up the members for a given group. It does not allow you to easily look up the groups for a given user. To allow the latter, you will need to add an additional data structure (often called a reverse index) mapping users back to groups.

userGroups
  uid1
    groupid1: true
    groupid2: true
  uid2
    groupid2: true
    groupid3: true

This means that you're duplicating data to allow for the additional use-case, which is quite common in NoSQL databases.

Also see:

Upvotes: 2

Related Questions