I have a chat app where I create new keys dynamically. Within each dynamic key, when a user sends a message, I create an object inside that key with its own dynamic key.
The structure is as follows:
https://xxxxx-default-rtdb.europe-west1.firebasedatabase.app/
├── chrome%3A%2F%2Fextensions%2F -> dynamically created
├── -O-VkRKionPx9eGQs9fs -> dynamically created
├── createdAt: 1718536488277
├── name: "uur37484225"
├── text: "dsd"
├── uid: "itZx6OYhT9QqZHkGiZ29cvUEard2"
The following rules configuration doesn't seem to be working:
{
"rules": {
".read": "auth != null",
".write": "auth != null",
"$url": {
"$id": {
".indexOn": ["createdAt"]
}
}
}
}
This is how I call the data:
const dbRef = ref(db, encodeFirebaseKey(currentUrl))
let queryRef
if (lastCreatedAt) {
queryRef = query(dbRef, orderByChild("createdAt"), limitToLast(20))
} else {
queryRef = query(dbRef, orderByChild("createdAt"), limitToLast(20))
}
get(queryRef)
.then((snapshot) => {
// Handle the snapshot
})
.catch((error) => {
console.error("Error fetching messages:", error)
})
The error I'm getting is:
Error: Index not defined, add ".indexOn": "createdAt", for path "/chrome%3A%2F%2Fextensions%2F", to the rules
What seems to be problem? I couldn't really find any documentation about this issue
The path in the error message is "/chrome%3A%2F%2Fextensions%2F"
, which is just a single segment: /$url
. Since you only define rules for the two-path segment /$url/$id
, there is no index defined on the first segment and you get an error.
You need to define the index on the level where you want to run the query, so:
{
"rules": {
...
"$url": {
".indexOn": ["createdAt"]
}
}
}
With this definition, Firebase creates an index on /$url
with the key and createdAt
value of each child node under it.