Although I found similar questions to mine, I couldn't solve the problem on my own.
In my '../models/user' model I want to find all users and put them into array, and return that array to the controller(where I will use the info).
Here is my code:
var mongoDatabase = require('../db');
var database = mongoDatabase.getDb();
function find() {
    var test;
    database.collection("customers").find().toArray( function(err, docs) {
        if(err) throw err;
        console.log(docs); //works fine
         //I'd like to return docs array to the caller
        test = docs;
    });
    console.log(test); //test is undefined  
}
module.exports = {
    find
};
I also noticed, that 'console.log(test)' goes before 'console.log(docs)'. I tried passing 'docs' argument as function parameter to 'find', but without result.
The best way is to use Promises. Do it like this.
function getUsers () {
  return new Promise(function(resolve, reject) {
     database.collection("customers").find().toArray( function(err, docs) {
      if (err) {
        // Reject the Promise with an error
        return reject(err)
      }
      // Resolve (or fulfill) the promise with data
      return resolve(docs)
    })
  })
}
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With