I want to query Firebase that contains an input. for example in the database structure below, I would like to query all nodes that contains "4140" so I use this code
var catref = Cataloguedatabase.ref("/Listing Search/");
return catref.once('value').then(function(snapshot){
snapshot.forEach(childSnapshot => {
let snapdb = childSnapshot.val();
let key = childSnapshot.key;
//use ES6 includes function
if(key.includes(schname)){
console.log(childSnapshot.val());
var searchresults = childSnapshot.val();
var container = document.getElementById('listing_gallery');
// container.innerHTML = '';
var productCard = `
<div class="col-sm-3">
<div class="card" onclick="gotoproduct(this);" id="${key}">
`
container.innerHTML += productCard;
}
})
})
This works but the problem is that it first query all the child and sort through the array.This is ok for node with few children but when it gets to thousands of children, it bees impractical. is there a away i can only query key the contains the value in firebase and if not how else can i implement this?
I want to query Firebase that contains an input. for example in the database structure below, I would like to query all nodes that contains "4140" so I use this code
var catref = Cataloguedatabase.ref("/Listing Search/");
return catref.once('value').then(function(snapshot){
snapshot.forEach(childSnapshot => {
let snapdb = childSnapshot.val();
let key = childSnapshot.key;
//use ES6 includes function
if(key.includes(schname)){
console.log(childSnapshot.val());
var searchresults = childSnapshot.val();
var container = document.getElementById('listing_gallery');
// container.innerHTML = '';
var productCard = `
<div class="col-sm-3">
<div class="card" onclick="gotoproduct(this);" id="${key}">
`
container.innerHTML += productCard;
}
})
})
This works but the problem is that it first query all the child and sort through the array.This is ok for node with few children but when it gets to thousands of children, it bees impractical. is there a away i can only query key the contains the value in firebase and if not how else can i implement this?
Share Improve this question edited Feb 21, 2018 at 1:43 jone2 asked Feb 21, 2018 at 1:33 jone2jone2 1911 gold badge6 silver badges18 bronze badges2 Answers
Reset to default 8As Doug says, there is no way to query for values that contain a certain string. But you can query for keys that start with a certain substring:
return catref.orderByKey().startAt("4140-").endAt("4140-\uf8ff").once('value').then(function(snapshot){
This will just match the child nodes whose key starts with 4140-
.
What you're asking is not possible with Firebase Realtime Database. There are no substring queries.
If you're only interested in the first four characters for your query, what you can do is store that string as a child inside that node, then orderByChild() on that child to find only those items that begin with a certain four character sequence.
You can read more about ordering in the documentation.