Skip to content Skip to sidebar Skip to footer

Firebase Returns False Value When There Is A Value Present In The Collection Using Node.js

I'm trying to verify a record in Firebase before registering the user with post request using node.js ***** Node.js Code **** function checkUserExist(email) { var userExist = f

Solution 1:

Data is loaded from Firebase asynchronously. By the time your return userExist runs, the data hasn't loaded yet.

This is easiest to see with some logging statements:

console.log('Before starting query');
userRef.orderByChild('email').equalTo(email).once('value').then(function (snapshot) {
  console.log('Got query results');
});
console.log('After starting query');

When you run this code, you get this output:

Before starting query

After starting query

Got query results

That is probably not the order you expected, but it explains precisely why your method returns the wrong value: the data hasn't been loaded yet by the time your function returns.

Any code that needs the data from the database, must either be inside the then() callback, or be called from there.

The common way to deal with asynchronous APIs is to return a promise:

functioncheckUserExist(email) {
    var userExist = false;
    return userRef.orderByChild('email').equalTo(email).once('value').then(function (snapshot) {
        return snapshot.exists();
    });
}

Now you can call checkUserExist like this:

checkUserExist(req.body.reg_email).then(function(userExists) {;
  console.log(userExists);
})

Note that here too, the userExists only has the correct value inside the then() callback.


If you're on a modern JavaScript environment, you can use async/await for the function call:

let userExists = awaitcheckUserExist(req.body.reg_email);
console.log(userExists);

Note that this is still doing the asynchronous call behind the scenes.

This is a very common problem for developers new to dealing with asynchronous APIs. I highly recommend you check out some of these previous answers:

Post a Comment for "Firebase Returns False Value When There Is A Value Present In The Collection Using Node.js"