I am making sure that my db doesnt have duplicate usernames or email addresses for my users using the unique: true attribute, but I am able to create users with duplicate usernames...so something isn't working. I have tried dropping the database, this did not solve the issue. Also in Model.on('index'), sometimes the error is not outputted to the console, sometimes it is. Strange.
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;
And my node router for adding users to the db...
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 });
});
});
});