This question arises from a homework question in the 10gen MongoDB class which uses Node.js, however, I'm not asking you to solve the homework (which is about Mongo) rather to explain relationship between two functions. In a session.js file, the method addUser
is called on a users
data object module like this
users.addUser(username, password, email, function(err, user) {
"use strict";
if (err) {
// this was a duplicate
if (err.code == '11000') {
errors['username_error'] = "Username already in use. Please choose another";
return res.render("signup", errors);
}
// this was a different error
else {
return next(err);
}
}
sessions.startSession(user['_id'], function(err, session_id) {
"use strict";
if (err) return next(err);
res.cookie('session', session_id);
return res.redirect('/welcome');
});
});
In the users data object module, there's a function this.addUser
like this
this.addUser = function(username, password, email, callback) {
"use strict";
// Generate password hash
var salt = bcrypt.genSaltSync();
var password_hash = bcrypt.hashSync(password, salt);
// Create user document
var user = {'_id': username, 'password': password_hash};
// Add email if set
if (email != "") {
user['email'] = email;
}
//node convention first arg to call back error, 2nd the actual data we're returning, callbackwith value if added user
// look in session.js file that uses the UsersDAO to get a sense of how this is being used and
// what type of callback is passed in.Task is to fill in code to add a user when one tries to signup
// TODO: hw2.3
callback(Error("addUser Not Yet Implemented!"), null);
}
We're supposed to implement the callback that enables the addition of the User into the mongo database. I'm not asking you to tell me that. Rather, the fourth argument to the users.addUser function is a callback function function(err, user) { }
. Also, the this.addUser
function has callback
as the fourth parameter, so the callback function from users.addUser
runs inside this.addUser?
Can you help clarify the relationship between these two? I know that a callback runs when a function has finished but I don't know why it's being passed into this.addUser