验证规则 以及错误信息处理

 

 

 

// 引入 mongoose 第三方模块 用来操作数据库
const mongoose = require('mongoose');
// 数据库连接
mongoose.connect('mongodb://localhost/playground', {
        useNewUrlParser: true,
        useUnifiedTopology: true
    })
    // 连接成功
    .then(() => console.log('数据库连接成功...'))
    // 连接失败
    .catch(err => console.log(err, '数据库连接失败...'));


const postSchema = new mongoose.Schema({
    title: {
        type: String,
        required: [true, '请传入文字标题'],
        minlength: [2, '文章长度不能小于2'],
        maxlength: [5, '文章长度不能超过5'],
        trim: true
    },
    age: {
        type: Number,
        min: 18,
        // 数字最大范围
        max: [100, '最大值不能超过100']
    },
    publishDate: {
        type: Date,
        // 默认值
        default: Date.now
    },
    category: {
        type: String,
        enum: {
            values: ['html', 'css', 'js', 'java'],
            message: '分类名选择错误...'
        }
    },
    author: {
        type: String,
        validate: {
            validator: v => {
                // 返回布尔值
                // true 验证成功
                // false 验证失败
                // v 要验证的值
                return v && v.length > 4
            },
            // 自定义错误信息
            message: '传入的值不符合验证规则'
        }
    }
});

const Post = mongoose.model('Post', postSchema);
Post.create({ author: 'abcd', title: '  aswwwwwwa    ', age: 225, category: 'jav2a' })
    .then(result => console.log(result))
    .catch(error => {
        // 获取错误信息对象
        const err = error.errors;
        // 循环错误对象
        for (var attr in err) {
            // 将错误信息打印到控制台中
            console.log(err[attr]['properties']['message']);
        }
    })

 

posted @ 2020-06-10 20:37  EricBlog  阅读(321)  评论(0编辑  收藏  举报