RealtimeDB index data by key

Issue

I have the following error while I try to query the members of my database:

FirebaseException ([firebase_database/index-not-defined]
Index not defined, add ".indexOn": "36a72WVw4weQEoXfk3T9gCtOL9n2", for path "/members", to the rules

I am trying to check if there is already a chat with those members in my database. This is what I am executing:

final snapshot = await _database.ref().child("members").orderByChild(firstUserId).equalTo(true).get();

This is my DB structure

DB

I have been searching how to index by key but I haven’t found anything. Is there something I am doing wrong?
I hope you can help me thanks in advance.

Solution

Indexes for keys are automatically created, but in this case you don’t even really need an index as you’re not querying on the key.

The easiest way to do this sort of check is:

final snapshot = await _database.ref().child("members").child(firstUserId).get();
if (snapshot.value == true) {
  ...
}

So we’re not using a query here, but are instead always reading the snapshot to then check its value.

The reason you can’t use a query is that it’d require an explicit/named index on every child node. For more on that, see my answer here: Firebase query if child of child contains a value

Answered By – Frank van Puffelen

Answer Checked By – Katrina (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *