javascript - Mongodb get results asynchronously -


here action users users collection

app.post('/login', function(req,res,next){     users = self._db.get('users', {}) }) 

and function in database class

this.get = function( col, opt )     {            var result = [],             opt    = opt || {};          query  = db.collection(col).find( opt );          query.each( function(err, doc)          {             console.log( doc );             if( doc != null )             {                 result.push( doc );             }         });          return result;     };   

and when log users object returns empty array when log each document inside function works

question how can result asyncronously?

you're missing callback function. since node.js asynchronous design, i/o ops need callback.

back example, suggest using monk , this:

var db = require('monk')('localhost/mydb'); var users = db.get('users');  app.post('/login', function(req, res) {    users.find({}, function(err, data) {      // remember handle error here, example;     // if (err) return res.send('error');            res.json(data);      });  }); 

basically, callback you've missing second argument of users.find function.


Comments

Popular posts from this blog

qt - Using float or double for own QML classes -

Create Outlook appointment via C# .Net -

ios - Swift Array Resetting Itself -