Pickles Pickles - 2 months ago 28
Javascript Question

How do I use equalsTo() in Firebase?

I have a database structure of:

newsfeed-21f5c

newsfeed3:9:2016:18:1:39
text: "5"
time: "3:9:2016:18:1:39"
timeStampFirebase: 1475661721607
newsfeed4:9:2016:11:16:10
number: 7
time: "4:9:2016:11:16:10"
timeStampFirebase: 1475723771672


And I tried running:

var search = firebase.database().ref("newsfeed");
search.orderByChild("number").equalTo(7).on("child_added", function(snapshot) {
console.log(snapshot.key);
});


And I keep getting a Firebase warning.


FIREBASE WARNING: Using an unspecified index. Consider adding ".indexOn": "number" at /newsfeed to your security rules for better performance


What I'm trying to achieve is to search for
newsfeeds
with the key of number that is equal to
7
.

I'm pretty new to Firebase so all help would be appreciated.

Answer

The message you are getting,

FIREBASE WARNING: Using an unspecified index. Consider adding ".indexOn": "number" at /newsfeed to your security rules for better performance

is not an error. Your code should work. Firebase supports indexing, which can drastically improve the speed of searches like this one. The warning you are seeing is Firebase asking you to configure the index for better performance.

How to do so:

Go to your Firebase console.

Look under Database -> Rules (one of the tabs).

There you can set permission rules AND indexes in JSON format. Copy paste this JSON in there:

{
  "rules": {
    "newsfeed": {
      ".indexOn": ["number"]
    }
  }
}

PS: use snapshot.getKey() to get the firebase key.