mongoose验证

在创建集合时可以设置当前字段的验证规则,不符合规则就插入失败

  • required:true -----必选字段
  • minlength:3 ------字符串最小长度不能小于3
  • maxlength:5 -------字符串最大长度不能大于5
  • min:2 ------最小数值不能小于2
  • mx:5 -----最大数值不能大于5
  • enum:[‘aaaa’,‘bbbbb’,‘ccccc’] — 只能传入这三个数据
  • validate —自定义验证器
//引用第三方模块
const mongoose = require('mongoose');
//连接数据库
mongoose.connect('mongodb://localhost/text', {
    useNewUrlParser: true,
    useUnifiedTopology: true
}).then(() => {
    console.log("数据库连接成功");
}).catch(err => {
    console.log(err);
})

//创建集合规则
const textSchema = new mongoose.Schema({
    name: {
        type: String,
        //必选字段
        required: [true, '你没传'],
        minlength: 2, //规定最小传入的长度
        maxlength: 5, //规定最大传入的长度
        trim: true //插入的数据不包含空格
    },
    age: {
        type: Number,
        min: 10,
        max: 50
    },
    publishDate: {
        type: Date,
        //默认值 是现在的时间
        default: Date.now
    },
    category: {
        type: String,
        //enum列举当前字段可以拥有的值  传其他的会报错
        enum:{
			 values:['a', 'b', 'c', 'd']
			 message:'只能传abcd' //自定义报错信息 
		}
    },
    author: {
        type: String,
        //自定义验证器
        validate: {
            validator: v => {
                //返回一个布尔值
                //true验证成功
                //false验证失败
                //v是要验证的值
                return v && v.length > 10;
            },
            //自定义错误信息
            message: '传入的值不符合验证规则'
        }
    }
})

//使用集合规则创建集合
const Jihe = mongoose.model('Jihe', textSchema);
//传入数据
Jihe.create({ name: 'fj', age: 18 }).then(
    (re) => {
        console.log(re);
    }
).catch((err) => {
    const error = err.errors;
    for (var k in error) {
        console.log(error[k]['message']); //打印错误信息
    }
})
});


猜你喜欢

转载自blog.csdn.net/forljnlearning/article/details/106842697