猫鼬验证仅在更改时 [英] Mongoose validation only when changed

查看:70
本文介绍了猫鼬验证仅在更改时的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

顺便说一句,钩子(prepost)将在 .

By the way, hooks (pre and post) will be removed in Mongoose 4.0.

这篇关于猫鼬验证仅在更改时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆