var result = [];
var user = db.collection('user');
var cursor = user.find();
cursor.toArray(function (err, doc) {
result = doc;
});
console.log(result); // console -> []
var result = [];
var user = db.collection('user');
var cursor = user.find();
cursor.toArray(function (err, doc) {
result = doc;
});
console.log(result); // console -> []
The problem is just Sync
You are experiencing this error because the find () method is asynchronous and in this case you have a Promise that may not have been resolved before console.log(result)
,
var result = [];
var user = db.collection('user');
var cursor = user.find();
//Aqui você tem uma Promisse
cursor.toArray(function (err, doc) {
result = doc;
});
console.log(result);//Caso a Promisse não tenha sido executada ainda, result ainda é um Array vazio
An interesting way to run could be like this, depending on your version of Node :
async function getResults() {
db.collection('user').find()
}
var results = await getResults();
results = results.toArray();
Dai your code looks like a synchronous code. The key here is the async / await command that waits for the promise results. More information, link link
It looks like this:
function find(query, callback) {
db.collection('user').find(query).toArray(function (err, doc) {
callback(err, doc);
});
}
find({name: 'Leandro'}, function (err, doc) {
let result = [];
result['user'] = doc;
console.log(result['user']); // console -> [ { name: 'Leandro', _id: 5a1d624e79a88f09fb805a35 } ]
});