Your code snippet has an unpleasant side effect:
var userId; tableOne.on('value', function (snapshot) { userId = snapshot.val().userId;
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;
This ensures that each userId value is written inside the function.
source share