Reputation: 9306
I'm trying to call this function on my model User(I'm using mongoose). like this:
UserSchema.statics.exists = function exists(req,email, callback) {
this.findOne({
email : email
}, function(err, user,callback) {
if(err) {
console.error(err);
return callback(err);
}
if(!user) {
// console.log("Not user");
return callback(null, false);// produce error
}
if(!user.valid) {
console.log("User invalid");
var hostname = req.headers.host;
// hostname = 'localhost:8080'
//var pathname = url.parse(req.url).pathname; // pathname = '/MyApp'
var base_url = 'http://' + hostname + '/activation?key=' + user.account_no;
user.verifyEmail(base_url, user, function(err, result) {
if(err) {
console.error(err);
return callback(err);
} else {
//if(email sent)
if(result) {
return callback("Please check your email to activate your account");
} else {
return callback("Activation error please contact WOWITO support");
}
}
});
}
return callback(null, user);
});
}
but then I got the following error:
node.js:201 throw e; // process.nextTick error, or 'error' event on first tick ^ TypeError: undefined is not a function
What did I do wrong?
Thanks,
Upvotes: 0
Views: 14126
Reputation: 123563
You have 2 different callback
variables, currently:
UserSchema.statics.exists = function exists(req, email, callback) { // 1st
this.findOne({
email : email
}, function(err, user, callback) { // 2nd
// ...
As they share the same identifier, the 2nd will "shadow" the 1st, rendering the 1st inaccessible within the anonymous function.
To use the 1st, you'll have to rename one of them -- perhaps, existsCallback
and/or findOneCallback
.
You may also be able to outright remove the 2nd, since it seems to be undefined
anyways:
UserSchema.statics.exists = function exists(req, email, callback) {
this.findOne({
email : email
}, function(err, user) {
// ...
You're also assuming that a value is being passed for callback
, which JavaScript doesn't actually require or enforce.
You can resolve this by testing for a value before calling:
if (callback) callback(...);
Or set it to a "no-op" function when it's not defined:
callback = callback || function() { return true; };
//...
callback(...);
Upvotes: 4