I am trying to get data from two tables like (fetch all users and their details)
tableOne.on('users', function (snapshot) {
userId = snapshot.val().userId; // line 1 (results like 1,2,3,4,5,6)
anotherTable.child('userdetails').child(userId).once('value', function(mediaSnap) {
// result // line 2
});
});
but the problem is line 1 executes first for the 6 times and then line 2 that n times resulting in everytime looking for 'where user id is - 6'...isn't joins supported in Firebase?
Any help is apreciated
I am trying to get data from two tables like (fetch all users and their details)
tableOne.on('users', function (snapshot) {
userId = snapshot.val().userId; // line 1 (results like 1,2,3,4,5,6)
anotherTable.child('userdetails').child(userId).once('value', function(mediaSnap) {
// result // line 2
});
});
but the problem is line 1 executes first for the 6 times and then line 2 that n times resulting in everytime looking for 'where user id is - 6'...isn't joins supported in Firebase?
Any help is apreciated
Share Improve this question edited Sep 7, 2014 at 16:59 Frank van Puffelen 599k85 gold badges888 silver badges858 bronze badges asked Sep 7, 2014 at 15:50 LuckyyLuckyy 1,0314 gold badges15 silver badges31 bronze badges 8 | Show 3 more comments2 Answers
Reset to default 10Your code snippet has a nasty side-effect:
var userId;
tableOne.on('value', function (snapshot) {
userId = snapshot.val().userId; // line 1 (results like 1,2,3,4,5,6)
anotherTable.child('userdetails').child(userId).once('value', function(mediaSnap) {
console.log(userId + ":" + mediaSnap.val().name);
});
});
You're not declaring userId
as a variable, which means that it becomes a global variable in JavaScript. And since the callback function executes asynchronously, there is a good chance that the global values will have changed by the time you need it.
The solution is simply to make userId
a local variable of the callback function:
tableOne.on('value', function (snapshot) {
var userId = snapshot.val().userId; // line 1 (results like 1,2,3,4,5,6)
anotherTable.child('userdetails').child(userId).once('value', function(mediaSnap) {
console.log(userId + ":" + mediaSnap.val().name);
});
});
This will ensure that each value of userId
is captured inside the function.
Solution for list join:
tableOne.orderByKey().on("value", function (snapshot) {
//console.log(snapshot.val());
snapshot.forEach(function (data) {
tableTwo.once('value').then(function (info) {
info = info.val();
});
});
});
on('users'
is not a valid event. You're probably lookinig foron('value'
oron('child_added'
. – Frank van Puffelen Commented Sep 7, 2014 at 16:51on('users'
toon('child_added'
). Can you update this jsbin so that it reproduces the problem? jsbin.com/zifeqi/1/edit – Frank van Puffelen Commented Sep 8, 2014 at 13:40