Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Node.js MongoDB collection.find().toArray returns nothing [duplicate]

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.

like image 232
Petar D. Avatar asked Dec 07 '22 17:12

Petar D.


1 Answers

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)
    })
  })
}
like image 80
Kamesh Avatar answered Dec 10 '22 05:12

Kamesh