0

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

1 Answer 1

4

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.