Monday, 10 October 2016

javascript - Node.js MongoDB collection.find().toArray returns nothing




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.


Answer



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)
})
})
}

No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...