1

Here is my action which will get all users from users collection

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

And this is my 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 I log users object it returns empty array but when I log each document inside function it works successfully

question is how can I get result asyncronously?

  • possible duplicate of [How to return value from an asynchronous callback function?](http://stackoverflow.com/questions/6847697/how-to-return-value-from-an-asynchronous-callback-function) – Blakes Seven Jul 30 '15 at 09:29

2 Answers2

1

You're missing the callback function. Since Node.js is asynchronous by design, all I/O ops need a callback.

Back to your example, I suggest you using monk and do something like this:

var db = require('monk')('localhost/mydb');
var users = db.get('users');

app.post('/login', function(req, res) {

  users.find({}, function(err, data) {

    // remember to handle error here, for example;
    // if (err) return res.send('error');      

    res.json(data);  

  });

});

Basically, the callback you've missing is the second argument of users.find function.

xmikex83
  • 945
  • 5
  • 14
0

Use a library like async to put a callback, where the result array can be returned when the each loop has finished iterating all the docs.

Async 'each' function

Kangcor
  • 1,179
  • 1
  • 16
  • 26