【问题标题】:Remove generated string from Mongoose schema with custom validation使用自定义验证从 Mongoose 模式中删除生成的字符串
【发布时间】:2021-01-23 00:26:18
【问题描述】:

我有一个带有自定义验证的架构。

const schema = new mongoose.Schema({
    username: {
        type: String,
        required: true,
        validate: {
            validator: /^[a-zA-Z0-9_]{3,16}$/, 
            message: "Usernames must be 3 to 16 characters long and contain only alphanumeric characters and underscores (_)."
        },
    },
    // ...other things
});

但是,当我输入无效的用户名时,验证消息如下所示:

User validation failed: username: Usernames must be 3 to 16 characters long and contain only alphanumeric characters and underscores (_).

如何去掉开头的字符串部分User validation failed: username:

【问题讨论】:

    标签: node.js mongoose schema


    【解决方案1】:

    格式嵌入到ValidationError class。没有猴子修补该类,我看不到轻松更改格式的方法。

    一种选择是在被模型抛出之前运行验证:

    const user = new User({ username: 'ab' })
    const error = user.validateSync()
    console.log(error.errors['username'].message)
    

    或者被抓到时处理ValidationError

    try {
      const user = new User({ username: 'ab' })
      await user.save()
    } catch (error) {
      if (error instanceOf mongoose.Document.ValidationError ) {
        console.log(error.errors['username'].message)
      }
    }
    

    【讨论】:

      【解决方案2】:

      要摆脱初始字符串,您可以简单地在显示之前对返回的字符串使用 split 方法。这是一个示例代码:

      let stringa = "User validation failed: username: Usernames must be 3 to 16 characters long and contain only alphanumeric characters and underscores (_)."; //replace this with error message
      let stringb = (stringa.split(":")[2]);
      
      console.log(stringb);//This displays the needed output string with Usernames 
      

      【讨论】:

        猜你喜欢
        • 2015-02-04
        • 2010-12-28
        • 1970-01-01
        • 1970-01-01
        • 2012-07-31
        • 1970-01-01
        • 2020-07-30
        • 1970-01-01
        • 2021-07-03
        相关资源
        最近更新 更多