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.

5
  • Judging from the documents of MongoDB you cannot pass arguments to the toArray why don't you simply do test = database.customers.find().toArray() Commented Jul 15, 2017 at 13:54
  • @Ozan still undefined Commented Jul 15, 2017 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 ? Commented Jul 15, 2017 at 13:58
  • @Ozan I'll start using Mongoose soon, but first I'd like to learn the basics Commented Jul 15, 2017 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 }; Commented Apr 5, 2021 at 20:22

1 Answer 1

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)
    })
  })
}
Sign up to request clarification or add additional context in comments.

12 Comments

What modules should I include? Is that 'jQuery'?
No, I have edited it, You should install an npm module 'q'
There is no need to add yet another module as Node.js has been supporting native Promises since around version 0.12 by itself.
Thanks for pointing this out. I have edited my answer.
@PetarD. You can also use the above code if you don't want to include the module
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.