Dorbagna
Dorbagna

Reputation: 315

How to check if firebase child contains any special value in JavaScript?

I am trying to get users who live in boston. Also I will use this method for other cities. So if it includes "bos" or "bo" I want to get the value anyway. I can't use equalTo in this case, because the database contains this words different types like "bostonmelie" "bostonspek".

I tried to use code like this but it didn't work:

var myref= firebase.database().ref();

myref.child('Users').orderByChild('Mothclass').on("value", function(snapshot) {
    //console.log(snapshot.val());
    snapshot.forEach(function(data) {
        //console.log(data.key);

        var n = data.key.includes("bos");
        console.log(n);


    });
});

Console log

00jszBe7JKba7DHwZKbK1G9ID7D3 checkfraud.js:105:9
1Fnyqg0T7ldDEPGppu9zOIa66ZE2 checkfraud.js:105:9
2LbwNtF1vWW0AWiKRum45xD04812 checkfraud.js:105:9
2kB7IwMAlzWK6l5T9hWXHUoCiL42 checkfraud.js:105:9
3ASeCkjaxrQrPtelENfkm1XvZfJ3 checkfraud.js:105:9
3JmFZ9fztRbnFhTLIbscp97IXjB3 checkfraud.js:105:9
3i588ADWdsU4PX86wyNnk961GBC2 checkfraud.js:105:9
3p6tvDw3SfdOp2KptgzK0Padn143 checkfraud.js:105:9
3yAWS85t4xc8awxiZhE20qFkUGd2 checkfraud.js:105:9 

Upvotes: 0

Views: 488

Answers (1)

Frank van Puffelen
Frank van Puffelen

Reputation: 599101

To query the database for keys that start with bos:

myref.child('Users').orderByKey().startAt('bos').endAt('bos\uf8ff').on("value", function(snapshot) {
  ...

The \uf8ff is simply the last known unicode character, so you're selecting all keys in a range that starts with bos and ends just before bot.

You'll note that I removed the orderByChild() call, since Firebase queries can only contain one orderBy.... This approach performs the filtering on the server, but that means you must possibly reorder the matching nodes on the client.

Upvotes: 3

Related Questions