dfgd
dfgd

Reputation: 455

node.js return data from find collection in loop

I am trying to return data from this function. Console.log(documents) successfully shows the data in console. But this works only in body of the function. I can't return this data to the template. What should I do? Should I use some async package for node.js, or can be accomplished somehow like this?

Thank you.

var projects = req.user.projects;
var docs = [];

db.collection('documents', function(err, collection) {
    for (i = 0; i < projects.length; i++) { 
        collection.find({'_projectDn': projects[i].dn},function(err, cursor) {
            cursor.each(function(err, documents) {
                if(documents != null){
                    console.log(documents);
                    //or docs += documents;
                }
            });
        });
    }
});

console.log(documents); // undefined

res.render('projects.handlebars', {
    user : req.user,
    documents: docs
});

Upvotes: 0

Views: 1259

Answers (1)

Lucas T.
Lucas T.

Reputation: 406

Those db functions are async, which means that when you try to log it, the function hasn't finished yet. You can log it using a callback, for example:

function getDocuments(callback) {
        db.collection('documents', function(err, collection) {
            for (i = 0; i < projects.length; i++) {
                collection.find({
                    '_projectDn': projects[i].dn
                }, function(err, cursor) {
                    cursor.each(function(err, documents) {
                        if (documents !== null) {
                            console.log(documents);
                            callback(documents);// run the function given in the callback argument
                        }
                    });
                });
            }
        });
    }
//use the function passing another function as argument
getDocuments(function(documents) {
    console.log('Documents: ' + documents);
});

Upvotes: 4

Related Questions