我想验证用户的电子邮件地址,但仅当它更改时.每次我保存到任何Entrant时,下面的代码似乎都很混乱,因此引发错误,表明电子邮件在保存时是重复的.
I want to validate a users email address, but only when it is changed. The following code seems to vlaidate everytime I make a save to any Entrant, and therefore is throwing an error that the email is a duplicate when it saves itself.
我如何正确验证创建者而不是每次进行编辑和保存的时间?
How do I properly validate when the Entrant is created rather than everytime I make an edit and save?
EntrantSchema.pre 'save', (next)-> user = this # Email Validation if (user.isModified('email')) console.log "Email has been changed".green.inverse # Unique Value EntrantSchema.path("email").validate ((email,respond) -> Entrant.findOne {email:email}, (err,user) -> if user respond(false) respond(true) ), "Oopsies! That e-mail’s already been registered"请注意,我认为validate()是第一次绑定的,因为当我更新用户时,我不会得到"Email已更改"的信息,这是我在console.login代码中登录的信息
Note that I think the validate() is being bound the first time, because when I update a user, I do not get "Email has been changed", which I'm console.logging in my code
推荐答案您使用错误的验证方式.猫鼬将验证器附加到架构而不是单个文档,这使它们成为全局文件.
You're using validation the wrong way. Mongoose attach validators to the schema and not to the single document, which makes them global.
因此,与其定义pre 'save'中的电子邮件,不如定义一个好的电子邮件验证器:
So, instead of validating email in pre 'save' you should define a good email validator:
EntrantSchema.path('email').validate ((email,respond) -> return respond true unless @isModified 'email' Entrant.count {email}, (err, count) -> respond count is 0 ), "Oopsies! That e-mail’s already been registered"但是,如果您希望电子邮件具有唯一性,那么最好使用unique索引:
But if you want email to be unique then it's best to use unique index instead:
EntrantSchema = new mongoose.Schema email: type: String, unique: true在验证器中检查唯一值可以使用同一封电子邮件更新两个用户.
Checking unique values in validators leaves the possibility to update two users with the same email.
顺便说一句,钩子(pre和post)将在 .
By the way, hooks (pre and post) will be removed in Mongoose 4.0.
更多推荐
猫鼬验证仅在更改时
发布评论