如何修复 "trim" 在猫鼬模式中不起作用

How to fix "trim" not working in mongoose schemas

我正在学习猫鼬并尝试在猫鼬模式中将 "trim" 设置为 true。但是它没有按预期工作。

我试过将 "lowercase" 等其他设置设置为 true 并且确实有效,所以我不知道为什么 "trim" 不起作用。

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'。

名称 "some user" 在字符串中间有 space。

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

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

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