嗨我想告诉用户,如果是用户名或电子邮件,那么我已经采取了哪一个但是我在保存功能中验证这一点的方式如果找到重复它会给你一个错误11000但是我不能指定哪一个是已经拿了。我希望错误提供一个索引或我可以放在if语句中的东西,解释哪一个是重复键,所以我可以更具体的错误。有没有办法可以做到这一点?也为什么我总是索引:0?每个领域都不应该有所不同吗?如果您有任何问题,请告诉我。
模式
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: []
})
发布操作
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 already taken'})
} else {
return res.send(err);
}
}
res.json({ success: true, message: 'User created'})
})
})
预存功能
user.pre('save', function(next) {
var user = this
// hash the password only if the password has been changed or user is 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 to hash
user.password = hash
next()
})
})
控制台日志错误
{ [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" }' }