【问题标题】:How to fix "trim" not working in mongoose schemas如何修复“修剪”在猫鼬模式中不起作用
【发布时间】:2019-11-07 23:11:55
【问题描述】:

我正在学习 mongoose,并尝试在 mongoose 架构中将“trim”设置为 true。但是它没有按预期工作。

我尝试将“小写”等其他内容设置为 true,但它确实有效,所以我不知道为什么“修剪”不起作用。

var userSchema = {
    name: {type: String, required: true, trim: true, lowercase: true},
    email: {
        type: String, 
        required: true,
        validate: function(value){
            if(!(validator.isEmail(value))){
                throw new Error("Not a valid email address");
            }
        },
        trim: true,
    },
    age: {
        type: Number,
        validate: function(value){
            if(value < 0){
                throw new Error("Age must be a positive number");
            }
        },
        default: 0
    },
    password: {
        type: String,
        required: true,
        minlength: 7,
        validate: function(value){
            if(value.toLowerCase().includes("password")){
                throw new Error(" Passwords should not contain the word 
'password ' ");
            }
        },
        trim: true
    }
}

var User = mongoose.model('User', userSchema);

var someuser = new User({
    name: "some user",
    age: 25,
    email: "user@something.com",
    password: "verysecurepassword"
})

我原以为新用户的名字是“someuser”,但结果却是“some user”。

【问题讨论】:

  • 'trim' 属性只删除字符串开头和结尾的空格,而不是中间的空格。

标签: javascript node.js mongodb mongoose mongoose-schema


【解决方案1】:

名称“某些用户”在字符串中间有空格。

您尝试执行的操作将不起作用,因为 trim 只会从字符串的开头和结尾删除空格。

【讨论】:

    【解决方案2】:

    请检查文档中的trim() 定义,您似乎正在尝试删除字符串中间不需要的字符,但trim() 仅在字符串@987654321 的开头和结尾删除它们@

    我建议您为此定义一个自定义 settermiddlewarepreSavemiddleware docs 挂钩并使用正则表达式转换字符串(如果您只想删除空格):str.replace( /\s\s+/g, ' ' )

    【讨论】:

      猜你喜欢
      • 2019-05-22
      • 2019-11-06
      • 2012-12-21
      • 1970-01-01
      • 2014-10-17
      • 1970-01-01
      • 2012-03-02
      • 1970-01-01
      • 2015-05-09
      相关资源
      最近更新 更多