问题描述
我将此模式与npm中的mongoose 3.0.3
一起使用:
I'm using this schema with mongoose 3.0.3
from npm:
var schema = new Schema({
_id: Schema.ObjectId,
email: {type: String, required: true, unique: true}
});
如果我尝试保存已经存在于db中的电子邮件,我希望得到一个ValidationError
,就像省略了required
字段一样.但是情况并非如此,我得到一个MongoError: E11000 duplicate key error index
.
If I try to save a email that is already in db, I expect to get a ValidationError
like if a required
field is omitted. However this is not the case, I get a MongoError: E11000 duplicate key error index
.
这不是验证错误(即使我删除了unique:true也会发生).
Which is not a validation error (happens even if I remove the unique:true).
知道为什么吗?
推荐答案
我更喜欢将其放在路径验证机制中,例如
I prefer putting it in path validation mechanisms, like
UserSchema.path('email').validate(function(value, done) {
this.model('User').count({ email: value }, function(err, count) {
if (err) {
return done(err);
}
// If `count` is greater than zero, "invalidate"
done(!count);
});
}, 'Email already exists');
然后它将被包装到ValidationError
中,并在调用validate
或save
时作为第一个参数返回.
Then it'll just get wrapped into ValidationError
and will return as first argument when you call validate
or save
.
这篇关于猫鼬唯一验证错误类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!