简体   繁体   中英

Node js Mongodb findOne not working Synchronously

I have a mongodb database with list of users and tokens. When I use query to findOne with query, its returning undefined. The code for findOne is as below:

var getApiTokenForUser = function(user){
console.log('get api token for :'+user);
var collection = db.collection(user_token_collection_name);
var result;
if(collection){
    console.log("cursor query: "+user);
    var cursor = collection.findOne({'user':user});
    console.log("cursor result: "+JSON.stringify(cursor));
}
return result;}

Logs that i printed for findOne is as below:

 get api token for :Zeus
 cursor query: Zeus
 cursor result: {}
 getApiTokenForUser return: undefined

But if I use find instead of findOne I can get list of users, but only in logs, it still returns undefined.

code for find is:

var getApiTokenForUser = function(user){
console.log('get api token for :'+user);
var collection = db.collection(user_token_collection_name);
var result;
if(collection){
    console.log("cursor query: "+user);
    var cursor = collection.find({'user':user});
    cursor.forEach(function(data) {
        result = data;
        console.log("cursor result: "+JSON.stringify(data));
    });
}
return result;}

and logs are:

cursor query: Zeus
getApiTokenForUser return: undefined
saveUserApiToken
cursor result: {"_id":"58a56442545e812a68f87bbe","user":"Zeus","token":"eyJhbGci
OiJIUzI1NiJ9.WmV1cw.mAQh65o-d2tOp_Fchi7iPm5pu_2f4QSXOAQ5JtoEe10"}

I want findOne to work synchronously. is there any way ?

You never assign result to anything in your first snippet. Your code (simplified):

var result; // you never assign anything to it
return result; // undefined

What you can do is to put the synchronous code inside the callback of findOne. For example:

collection.findOne({'user':user}, function(error,user) {    
     //Synchornous code here
})

Hope my answer was helpful for you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM