0

index.js

console.log(friender_database.checkIsExist(event.source.userId));`

database.js

function checkIsExist(user_Id) {
  var result = false;
     MongoClient.connect("mongodb://localhost:27017/friender_database", function(err,db){
      db.collection('users_list',function(err,collection){
       collection.find({}).toArray(function(err,items){
            if(err) throw err;
            console.log("We found "+items.length+" results!");            
            result = true;
        });
      });
      db.close(); 
    });
    return result; 
}

I think it can check is user exist or not. but it result = true; can't work, i guess it scopes problem? or ...? some else i need to research?

Neil Lunn
  • 148,042
  • 36
  • 346
  • 317
LiHao
  • 290
  • 3
  • 13
  • the mongo query function is async. The return statement will be executed before the query return results. So the result of the function will always be false. – gvmani Jun 28 '17 at 11:57
  • so... result = true it's work but async let result = false faster than true? – LiHao Jun 28 '17 at 11:58
  • how to solve this situation... i don't want index.js have a lot database operation:(( – LiHao Jun 28 '17 at 12:00
  • sorry not sure about the correctness of the query. I was just pointing out the async nature of JS. – gvmani Jun 28 '17 at 12:00

0 Answers0