【发布时间】:2015-07-24 04:41:01
【问题描述】:
我在使用 res.send(err) 向用户输出错误时遇到问题,该问题在 Mongoose 用户架构“保存”函数的回调中被调用。我想指出,当我使用 console.log(err) 时,它显示了预期的错误(例如用户名太短),但是 res.send 在发送带有 POST 值的请求时在 PostMan 中输出“{}”应该会导致错误。
我还想知道我是否应该在我的路由器或我的 Mongoose 用户模式 .pre 函数中进行输入验证?在那里进行验证似乎是正确的,因为它使我的 Node 路由器文件更加干净。
这是有问题的代码...
app/routes/apiRouter.js
var User = require('../models/User');
var bodyParser = require('body-parser');
...
apiRouter.post('/users/register', function(req, res, next) {
var user = new User;
user.name = req.body.name;
user.username = req.body.username;
user.password = req.body.password;
user.save(function(err) {
if (err) {
console.log(err);
res.send(err);
} else {
//User saved!
res.json({ message: 'User created' });
}
});
});
...
app/models/User.js
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var bcrypt = require('bcrypt-nodejs');
var validator = require('validator');
var UserSchema = new Schema({
name: String,
username: { type: String, required: true, index: {unique: true} },
password: { type: String, required: true, select: false }
});
UserSchema.pre('save', function(next) {
var user = this;
if (!validator.isLength(user.name, 1, 50)) {
return next(new Error('Name must be between 1 and 50 characters.'));
}
if (!validator.isLength(user.username, 4, 16)) {
return next(new Error('Username must be between 4 and 16 characters.'));
}
if (!validator.isLength(user.password, 8, 16)) {
return next(new Error('Password must be between 8 and 16 characters.'));
}
bcrypt.hash(user.password, false, false, function(err, hash) {
user.password = hash;
next();
});
});
UserSchema.methods.comparePassword = function(password) {
var user = this;
return bcrypt.compareSync(password, user.password);
};
module.exports = mongoose.model('User', UserSchema);
【问题讨论】:
标签: node.js validation error-handling mongoose