仅在更改时进行Mongoose验证

时间:2013-08-05 16:39:25

标签: node.js mongodb express mongoose

我想验证用户的电子邮件地址,但仅限于更改时。每次我对任何Entrant进行保存时,下面的代码似乎都是vlaidate,因此抛出一个错误,即电子邮件在保存时会重复。

如何在创建参与者时正确验证,而不是每次进行编辑和保存时?

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()是第一次被绑定,因为当我更新用户时,我没有得到“电子邮件已被更改”,我在我的代码中是console.logging

1 个答案:

答案 0 :(得分:3)

你正在以错误的方式使用验证。 Mongoose将验证器附加到模式而不是单个文档,这使它们成为全局文件。

因此,您应该定义一个好的电子邮件验证工具,而不是验证pre 'save'中的电子邮件:

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索引:

EntrantSchema = new mongoose.Schema
  email: type: String, unique: true

检查验证器中的唯一值可以使用相同的电子邮件更新两个用户。

顺便说一下,钩子(prepostwill be removed in Mongoose 4.0