models/user.js
var user = module.exports = mongoose.model('user',userschema); module.exports.getuserbyusername = function(username, callback){ var query = {username:username}; user.findone(query, callback); } module.exports.createuser = function(newuser, callback){ user.getuserbyusername(newuser.username,function(err,username){ if(err) throw err; // username exists if(username){ // how can handle error? console.log('username exists'); } else{ bcrypt.hash(newuser.password, 10, function(err,hash){ if(err) throw err; newuser.password = hash; newuser.save(callback); }); } }); }
router/users.js
router.post('/register',function(req,res,next){ var username = req.body.username; var password = req.body.password; var newuser = new user({ username:username, password:password }); req.checkbody('username','username field required').notempty(); req.checkbody('password','password field required').notempty(); var errors = req.validationerrors(); if(errors){ res.render('register',{ errors: errors, username: username, password: password }); } else{ user.createuser(newuser,function(err,user){ if(err) throw err; req.flash('success','you registered , may log in'); res.location('/'); res.redirect('/'); }); } });
above codes user registration code.
in models/user.js
i made function 'createuser' new user, , find whether exists. however, don't know how throw custom error, "user exists"..
what should do?
i tried :
// username exists if(username) { callback(new error('username exists')); }
but didn't work!
to throw error message "username exsits", should do?
thank reading. :)
p.s) models/user.js -> createuser function defined.
routes/users.js -> createuser function attached work.
you handle following node best practices , return error in callback
module.exports.createuser = function(newuser, callback){ user.getuserbyusername(newuser.username, function(err, username) { if(err) throw err; if(username){ callback('username exists', null); // callback(error, data) ... ......
then catch it
router.post('/register',function(req,res,next){ ... data if(errors){ res.render('register',{ errors: errors, username: username, password: password }); } else { user.createuser(newuser,function(err,user){ if(err) { res.render('register',{ errors: err, // username exists username: username, password: password }); } else { req.flash('success','you registered , may log in'); res.location('/'); res.redirect('/'); } }); } });
Comments
Post a Comment