How to assign the callback variable "cursor.toArray (err, doc)" to an external variable?

1
var result = [];
var user = db.collection('user');
var cursor = user.find();
cursor.toArray(function (err, doc) {
    result = doc;
});
console.log(result); // console -> []
    
asked by anonymous 10.12.2017 / 16:31

2 answers

2

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

    
10.12.2017 / 19:50
0

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 } ]
});
    
11.12.2017 / 02:09