简体   繁体   English

Node js Mongodb findOne无法同步工作

[英]Node js Mongodb findOne not working Synchronously

I have a mongodb database with list of users and tokens. 我有一个包含用户和令牌列表的mongodb数据库。 When I use query to findOne with query, its returning undefined. 当我使用查询来查找带有查询的findOne时,其返回未定义。 The code for findOne is as below: findOne的代码如下:

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: 我为findOne打印的日志如下:

 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. 但是,如果我使用find而不是findOne,则可以获取用户列表,但仅在日志中,它仍返回未定义。

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. 我希望findOne同步工作。 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. 您可以做的是将同步代码放入findOne的回调中。 For example: 例如:

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

Hope my answer was helpful for you. 希望我的回答对您有所帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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