0

How do I get the main function returning the value of the 'collection' anonymous function after it has been executed?

function getStudentStatus(name, course, term){
    MongoClient.connect(url, function(err, db){
        if(err) throw err;
        var db_instance = db.db('newdb');
        db_instance.collection('students').findOne({}, function(err, res){
            if(err) throw err;
            console.log('[Mongo Database]: '+ res.name);
        });
    });
}
  • 1
    You don't. The core problem here is that you are issuing a connection **"inside"** of an individual request to obtain data. Database connections should persist for the lifecycle of your application. So you "connect once" and then share that connection around the rest of your application. Look at [How do I manage MongoDB connections in a Node.js web application?](https://stackoverflow.com/questions/10656574/how-do-i-manage-mongodb-connections-in-a-node-js-web-application) and generally search the wider internet on that phrase. There are plenty of examples out there. – Neil Lunn Apr 15 '18 at 23:45
  • Also, related you should get a basic understanding of [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call). Lots of material there regarding both legacy and modern approaches. The modern driver supports [Promises](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise), and you should get used to understanding how to use them. – Neil Lunn Apr 15 '18 at 23:49
  • Thank you, I removed the Db connection from that function and it works very well. – Victor Michael Kosgei Apr 16 '18 at 11:08

0 Answers0