3

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.

Petar D.
  • 149
  • 1
  • 5
  • 15
  • Judging from the documents of MongoDB you cannot pass arguments to the toArray why don't you simply do ```test = database.customers.find().toArray()``` – Ozan Jul 15 '17 at 13:54
  • @Ozan still undefined – Petar D. Jul 15 '17 at 13:57
  • @Petar D. Well I just tested in my local development and it did return all the documents. I am not sure what's causing it. Why don't you use mongoose ? – Ozan Jul 15 '17 at 13:58
  • @Ozan I'll start using Mongoose soon, but first I'd like to learn the basics – Petar D. Jul 15 '17 at 14:02
  • You can try this, var mongoDatabase = require('../db'); var database = mongoDatabase.getDb(); function find() { return database.collection("customers").find().toArray(); } module.exports = { find }; – Pavneet Kaur Apr 05 '21 at 20:22

1 Answers1

15

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)
    })
  })
}
Kamesh
  • 1,122
  • 9
  • 12