我确保我的数据库没有使用unique:true属性为我的用户提供重复的用户名或电子邮件地址,但是我能够创建具有重复用户名的用户......所以某些东西不起作用。我试过删除数据库,这没有解决问题。同样在Model.on('index')中,有时错误不会输出到控制台,有时也会输出。奇怪。
var userSchema = mongoose.Schema({
username: {type: String, unique: true, required: true},
password: {type: String, required: true, select: false},
emailAddress: {type: String, unique: true, required: true},
emailVerified: {type: Boolean, default: false},
emailVerificationCode: {type: Number},
friends: []
});
userSchema.pre('save', function(next) {
var user = this;
if (!user.isModified('password')) return next();
bcrypt.genSalt(10, function(err, salt) {
if (err) return next(err);
bcrypt.hash(user.password, salt, function(err, hash) {
if (err) return next(err);
user.password = hash;
next();
});
});
});
var User = mongoose.model('User', userSchema);
User.on('index', function(err) {
console.log(err);
});
module.exports = User;
我的节点路由器用于将用户添加到数据库...
router.post('/register', function(req, res, next) {
var newUser = new User({ username: req.body.username, password: req.body.password, emailAddress: req.body.email });
newUser.save(function(err, newUser) {
if (err) return next(err);
newUser.sendVerificationEmail(function(err, isSent) {
if (err) return next(err);
res.json({ success: true });
});
});
});