Reputation: 839
I am new to node js and its callback scheme. I am having difficulty understanding some parts of this code, as explained hereafter:
Code found in a mongoUtil.js module:
var _db;
module.exports = {
connectToServer: function(callback) {
MongoClient.connect(url, function(err, client) {
_db = client.db('MyDB');
return callback(err);
});
},
};
Code found in my app.js module:
mongoUtil.connectToServer(function(err, client) {
if (err) console.log(err);
...
});
Questions:
i) Why is there a "function(err, client)" passed from the app.js file to the connectToServer function in the mongoUtil file?
Upvotes: 0
Views: 59
Reputation: 28316
What value is passed to the "client" parameter of the MongoClient.connect function, which is used within the function itself (client.db('MyDB'))?
The client
parameter isn't passed to the connect function, it is an argument in the definition of an anonymous function, that anonymouns function is then passed to the connect function.
The MongoClient.connect function is defined here: https://github.com/mongodb/node-mongodb-native/blob/master/lib/mongo_client.js#L205-L220
It accepts 2 arguments: a URL and a function
It expects that the provided function will also accept 2 arguments: error and client.
When the connect function finishes its work, it will call the function that it was passed instead of returning a value.
Why is there a "function(err, client)" passed from the app.js file to the connectToServer function in the mongoUtil file?
It would appear that this app.js and mongoUtils.js were not created to work together.
The connectToServer
exported from the function sets a module variable _db
instead of passing a client to the callback, which the function call in app.js appears to be expecting.
Upvotes: 1