简体   繁体   中英

Return value from a mongodb call from nodejs

How do I return an array from a mongojs query. I have the below query executed with nodejs, into a locally running mongodb database. Mongojs is handling the transaction. 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.

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. 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:

function (user) {
    return user;
}

And, at least with the current standard of ECMAScript 5 , you can't get around this. 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.

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