Reputation: 71
I m new to Node js and firebase. I m trying to fetch JSON data stored in my firebase database depending upon some search criteria.
In the following example:
The variable childname is key to whose value we have to search (col1) and findvalue is value for that key( value for col1 to be)
for this I tried the following codes:
function searchKeyValue(headNode,childname,findvalue) {
var ref = firebase.database().ref("data/"+headnode);
ref.orderByKey().on("child_added", function(snapshot) {
//extracting Query
ref.orderByChild(childname).equalTo(findvalue).on("value",function (snapshot) {
console.log(snapshot.val());
});//end of Query
});//end oder by key
}// end of function
function searchKeyValue(headnode,childname,findvalue) {
var ref = firebase.database().ref("data");
nextref=ref.child(headnode);
nextref.orderByChild(childname).equalTo(findvalue).on("value",function (snapshot) {
console.log(JSON.stringify(snapshot.val()));
})
}
but both fails to provide me the desired output: OUTPUT DESIRED is :
{1:"152",2:"233.69",3:"-191.7",4:"133.69",5:"-199.769",6:"AMUKH",7:"4",{"port":4},8:"NTP",9:{"Dup":12345}]}
But getting:
{"-KOZ2Md3NZ_vWddAIBj3":[null,"152","233.69","-191.7","133.69","-199.769","AMUKH","4",{"port":4},"NTP",{"Dup":12345}]}
[Note: I missed all keys of my saved data I m getting only values to that keys...]
Upvotes: 1
Views: 12916
Reputation: 9
var v = firebase.database().ref().child("data");
var no;
count = 0;
v.on("child_added", snap => {
count++;
no = snap.child("HeadNode").val();
//console.log(no , count);
});
Upvotes: 0
Reputation: 598708
When you execute a query against the Firebase Database, there will potentially be multiple results. So the snapshot contains a list of those results. Even if there is only a single result, the snapshot will contain a list of one result.
I can't figure out what your first snippet is supposed to do. But the second snippet can be made to work with:
function searchKeyValue(headnode,childname,findvalue) {
var ref = firebase.database().ref("data");
nextref=ref.child(headnode);
nextref.orderByChild(childname).equalTo(findvalue).on("value",function (snapshot) {
snapshot.forEach(function(childSnapshot) {
console.log(JSON.stringify(childSnapshot.val()));
});
})
}
Alternatively you can listen for child_added
, which fires for each child individually:
function searchKeyValue(headnode,childname,findvalue) {
var ref = firebase.database().ref("data");
nextref=ref.child(headnode);
nextref.orderByChild(childname).equalTo(findvalue).on("child_added",function (childSnapshot) {
console.log(JSON.stringify(childSnapshot.val()));
})
}
Upvotes: 2