2013-07-10 57 views
0

我试图用猫鼬验证独特的用户名字段为用户模型验证唯一的用户名

User.schema.path('username').validate(function(value, done) { 
    User.findOne({username: value}, function(err, user) { 
    if (err) return done(false); 
    if (user) return done(false); 

    done(true); 
    }); 
}, "exists"); 

,当我创建新用户这一切的伟大工程。但是,当更新用户数据时,我的验证失败。基本上,因为我正在尝试编辑相同的用户,所以失败了。 I.E.当更新用户名= bob时,验证方法发现bob并失败。

我有独特的:在我的模型上这个领域是真的,所以mongodb将验证它,只是没有我的猫鼬验证。

var UserSchema = new Schema({ 
    username: { type: String, required: true, unique: true }, 
    password: { type: String, required: true } 
); 

但是与让蒙戈告诉我,我不能插入数据的问题是有没有很好的方法来提取有意义的错误信息发送回客户端。即'对不起的用户名已存在,请选择一个新的'

基本上我只能想办法解决这个问题,如果猫鼬通过我的验证器我想验证的实际对象,而不仅仅是值。然后,我可以比较_id的,即

if (current._id == new._id) //this is the same user don't fail validation on unique username 
+0

可能的重复[有没有在猫鼬验证过程中引用当前模型的\ _id字段?](http://stackoverflow.com/questions/17507522/is-there-a-way-to-refer -mo-the-current-models-id-field-validation-in-mo) – JohnnyHK

+0

是的,先生,谢谢! – lostintranslation

回答