【问题标题】:Mongoose validation only when changed仅在更改时进行 Mongoose 验证
【发布时间】:2013-08-06 11:07:03
【问题描述】:

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

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

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() 是第一次绑定,因为当我更新用户时,我没有收到“电子邮件已更改”,我是控制台。登录我的代码

【问题讨论】:

  • 或许可以使用this.isModifies('email') (see docs),但我建议您改用unique index
  • 我有isModified(),见上面的代码。出于其他原因,我需要使用自己的验证器
  • 仅供其他读者参考:mongoosejs.com/docs/… 不应为此使用唯一索引

标签: node.js mongodb express mongoose


【解决方案1】:

您以错误的方式使用验证。 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

【讨论】:

  • 太棒了,谢谢。我在验证器内部寻找的是@isModifed。谢谢你:)
猜你喜欢
  • 2015-05-09
  • 2015-01-02
  • 1970-01-01
  • 2017-10-06
  • 2017-01-03
  • 2020-04-26
  • 2010-11-26
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多