How to make joins on Firebase tables

I am trying to get data from two tables, such as (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 that line 1 is executed first for 6 times, and then line 2, which n times leads to the fact that each time it looks for "where the user ID is 6" ... is not combined in Firebase?

Any help would be appreciated

+6
source share
1 answer

Your code snippet has an unpleasant 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 do not declare userId as a variable, which means that it becomes a global variable in JavaScript. And since the callback function runs asynchronously, there is a good chance that the global values ​​will change by the time you need it.

The solution is to make userId 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 ensures that each userId value is written inside the function.

+7
source

Source: https://habr.com/ru/post/974939/


All Articles