简体   繁体   English

从nodejs的mongodb调用返回值

[英]Return value from a mongodb call from nodejs

How do I return an array from a mongojs query. 如何从mongojs查询返回数组。 I have the below query executed with nodejs, into a locally running mongodb database. 我将以下查询与nodejs一起执行到本地运行的mongodb数据库中。 Mongojs is handling the transaction. Mongojs正在处理这笔交易。 My question is; 我的问题是; how can I return an array from the below function call. 如何从下面的函数调用返回一个数组。

    var databaseUrl = "users";
    var collections = ["users","reports"]; 
    var db = require('mongojs').connect(databaseUrl, collections );

    function usernameFromId(callback){
      db.users.find({}, function(err, result) {
        if(err || !result) console.log("Error");
          else{
           callback(result);
          }
      });
     };


    var x = usernameFromId(function(user){
    return user;
    });

    console.log(x);

Here x is undefined, how can I make a return value such that x will be an array where I can access elements by x.name, x.email etc. 这里x是未定义的,我如何创建一个返回值,使x成为一个数组,我可以通过x.name,x.email等访问元素。

This is what is held in the database. 这是数据库中的内容。

 { "_id" : ObjectId("4fb934a75e189ff2422855be"), "name" : "john", 
 "password":"abcdefg", "email" : "john@example.com" }
 { "_id" : ObjectId("4fb934bf5e189ff2422855bf"), "name" : "james", 
 "password" :"123456", "email" : "james@example.com" }

You can't usefully return with asynchronous functions. 您无法使用异步函数return You'll have to work with the result within the callback: 您必须在回调中处理结果:

usernameFromId(function(user){
    console.log(user);
});

This is due to the nature of asynchronous programming: " exit immediately , setting up a callback function to be called sometime in the future. " This means that: 这是由于异步编程的本质:“ 立即退出 ,设置将来某个时候调用的回调函数。 ”这意味着:

var x = usernameFromId(...);

is evaluated, in its entirety (including setting x to the undefined value returned from usernameFromId ), before the callback is actually called: 在实际调用回调之前,完整地评估(包括将x设置为从usernameFromId返回的undefined值):

function (user) {
    return user;
}

And, at least with the current standard of ECMAScript 5 , you can't get around this. 而且,至少在ECMAScript 5的当前标准下,你无法解决这个问题。 As JavaScript is single-threaded, any attempt to wait for the callback will only lock up the single thread, keeping the callback and the return user forever pending in the event queue. 由于JavaScript是单线程的,因此任何等待回调的尝试都只会锁定单个线程,从而使回调和return user永远在事件队列中保持挂起状态。

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

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