node.jsmongodbmongoosenowjs-sockets

Query MongoDB (via MongooseJS) and save result in Javascript variable?


Server-side:

var test;

UserModel.findOne({name: 'guest'}, function(err, user) {
    test = user.name;
});

console.log(test);

This does not work. The value of "test" is not logged in the console. Moving console.log inside the "UserModel.findOne" callback function works though.

Question

How do I get the "user.name" out of my database and into a variable?

Additional Details

The reason why I am doing this is because I want to use Mongoose with NowJS like this (grab some detail from MongoDB, send it to client using NowJS etc):

nowjs.on('connect', function () { 

    var test;

    UserModel.findOne({name: 'guest'}, function(err, user) {
            test = user.name;
            }); 

    this.now.receiveMessage(test);
});

But this is strictly speaking not a question about NowJS.


Solution

  • You'd have to put the NowJS call inside the callback:

    var now = this.now;
    UserModel.findOne({name: 'guest'}, function(err, user) {
        now.receiveMessage(user.name);
    });