mongodb - Mongo username and email unique fields validation -
hi want tell user 1 taken if username or email way im validating in save function if finds duplicate give error 11000 cant specify 1 taken. want error give index or can put in if statement explaining 1 duplicate key can more specific error. there way can accomplish this? why im getting index: 0? shouldn't different each field? let me know if have questions.
schema
var user = db.schema({ name: { type: string, required: true}, username: { type: string, required: true, index: { unique: true }}, email: { type: string, required: true, index: { unique: true }}, password: { type: string, required: true, select: false}, admin: { type: boolean, required: true}, verify: { type: boolean, required: true}, created_at: { type: string, required: true, default: date.now }, updated_at: { type: string, required: true, default: date.now }, campaigns_donated: [] })
post action
router.post('/register', function(req, res){ var user = new user() user.name = req.body.name user.username = req.body.username user.email = req.body.email user.password = req.body.password user.admin = false, user.verify = false user.save(function(err) { if (err) { console.log(err); if (err.code == 11000) { return res.json({ success: false, message: 'username or email taken'}) } else { return res.send(err); } } res.json({ success: true, message: 'user created'}) }) })
pre save function
user.pre('save', function(next) { var user = // hash password if password has been changed or user new if (!user.ismodified('password')) { return next() } //generate hash function bcrypt.hash(user.password, 10, function(err, hash) { if (err) return next(err) //change password hash user.password = hash next() }) })
console log error
{ [mongoerror: e11000 duplicate key error index: reachpeeps.users.$username_1 dup key: { : "xandor" }] name: 'mongoerror', message: 'e11000 duplicate key error index: reachpeeps.users.$username_1 dup key: { : "xandor" }', index: 0, code: 11000, errmsg: 'e11000 duplicate key error index: reachpeeps.users.$username_1 dup key: { : "xandor" }' }
Comments
Post a Comment