As some have noted, collection.find
is asynchronous, so when you reach the next line in userExists
(the line where you've got return ret > 0?true:false;
), it's too early and the value of ret
hasn't been set. Anywhere outside of the callback to collection.find
(and any functions it calls in turn), the query hasn't happened yet.
There is (basically) no way to "pause" userExists
until after the query, so you need to change your whole approach. What you need is the Continuation Pattern. This means that whatever you're doing with the result of collection.find
has to happen in the callback.
I don't know what you're trying to do with ret
, so this might mean big changes to how your code is organized. Here's an outline that I hope will give you the general idea:
function processResultAndDisplayToTheUser(ret) {
//everything that needs to happen after the value of ret is set
if (ret > 0) {
doSomething();
} else {
doSomethingElse();
}
}
function userExists(db, uid){
var collection = db.get('users');
//ret doesn't exist here
collection.find({"uid":uid}, {}, function(e,docs){
var ret = docs.length;
//ret finally exists, so pass it to a function and use it
processResultAndDisplayToTheUser(ret);
});
//ret doesn't exist here either
}
//ret still doesn't exist here