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 already exists
if(username){
// How can handle this error?
console.log('username already exists');
} else{
bcrypt.hash(newUser.password, 10, function(err,hash){
if(err) throw err;
newUser.password = hash;
newUser.save(callback);
});
}
});
}
路由器/ 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 is required').notEmpty();
req.checkBody('password','Password field is 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 are now registered and may log in');
res.location('/');
res.redirect('/');
});
}
});
以上代码是关于用户注册码。
models / user.js中的
我做了一个功能' createUser'获得一个新用户,并查找它是否已存在。但是,我不知道如何抛出自定义错误,"用户已存在" ..
我该怎么办?
我试过这样:
// username already exists
if(username) {
callback(new Error('username already exists'));
}
但它没有用!
要在邮件中输入错误"用户名已经存在",我该怎么办?
感谢您的阅读。 :)
P.S) models / user.js - > createUser函数已定义。
routes / users.js - > createUser函数已附加到工作中。
答案 0 :(得分:0)
您可以通过遵循Node最佳做法并在回调中返回错误来处理此问题
select = map . (last .) . take
然后抓住它
select = map . flip (!!) . subtract 1