猫鼬验证仅在更改时

编程入门 行业动态 更新时间:2024-10-28 18:27:45
本文介绍了猫鼬验证仅在更改时的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我想验证用户的电子邮件地址,但仅当它更改时.每次我保存到任何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.

更多推荐

猫鼬验证仅在更改时

本文发布于:2023-10-26 11:15:31,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1529970.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!