Node开发--->11_Node.js_mongoDB验证规则

2.6 mongoose验证

在创建集合的时候,可以为当前集合当中的字段去设置一些格式上的验证规则。比如:当前字段的类型是字符串类型,我们可以设置字段在存入值的时候,限定字符串的最大和最小长度,当验证成功的时候,当前的字段就可以插入集合。

验证规则之required:true必传字段

在创建集合的时候,规定了集合可以拥有哪些字段,默认情况下这些字段都是可选的

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

//创建集合规则
const postScheam = new mongoose.Schema({
    // title: String,是曾经的写法,如果这样写就指定不了验证规则
    //现在修改写法如下:
    title: {
        type: String,
        //现在如果不传title这个字段就会报错
        required: true
    }
});
//利用规则创建集合
const Post = mongoose.model('Post', postScheam);

//传一个空对象,不插入type字段,那么就会报错
//因为集合规则中有限制:如果不传type,就不会插入成功
Post.create({}).then(res => console.log(res))

运行后

同时我们还可以自定义更加友好的报错信息

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

//创建集合规则
const postScheam = new mongoose.Schema({
    // title: String,是曾经的写法,如果这样写就指定不了验证规则
    //现在修改写法如下:
    title: {
        type: String,
        //定义更加优化的报错信息
        required: [true, '请传入文章标题']
    }
});
//利用规则创建集合
const Post = mongoose.model('Post', postScheam);

Post.create({}).then(res => console.log(res))

运行后

验证规则之minlength,maxlength

针对于字符串,限定字段的最大最小长度

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

//创建集合规则
const postScheam = new mongoose.Schema({
    title: {
        type: String,
        required: [true, '请传入文章标题'],
        //限定title的最下和最大长度的
        minlength: 2,
        maxlength: 5
    }
});
//利用规则创建集合
const Post = mongoose.model('Post', postScheam);

//传入的长度与规定的长度不符合,也报错
Post.create({ title: 'a' }).then(res => console.log(res))

运行后

minlength和maxlength都可以自定义错误信息,形式同require

验证规则之trim

去除字符串两边的空格

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

//创建集合规则
const postScheam = new mongoose.Schema({
    // title: String,是曾经的写法,如果这样写就指定不了验证规则
    //现在修改写法如下:
    title: {
        type: String,
        required: [true, '请传入文章标题'],
        minlength: 2,
        maxlength: 5,
        //去除字符串两边的空格
        trim: true
    }
});
//利用规则创建集合
const Post = mongoose.model('Post', postScheam);

//trim去除字符串两边的空格 插入到数据库后左右两边无空格
Post.create({ title: '         aa      ' }).then(res => console.log(res))

验证规则之min,max

针对数值字段类型

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

//创建集合规则
const postScheam = new mongoose.Schema({:
    title: {
        type: String,
        required: [true, '请传入文章标题'],
        minlength: 2,
        maxlength: 5,
        trim: true
    },
    age: {
        type: Number,
        min: 18,
        max: 100
    }
});
//利用规则创建集合
const Post = mongoose.model('Post', postScheam);

//年龄小于18 报错
Post.create({ title: 'aa', age: 10 }).then(res => console.log(res))

验证规则之default

对于非可选字段,当插入数据的时候,不为该字段赋值,那么就会自动有一个默认值

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

//创建集合规则
const postScheam = new mongoose.Schema({
    // title: String,是曾经的写法,如果这样写就指定不了验证规则
    //现在修改写法如下:
    title: {
        type: String,
        required: [true, '请传入文章标题'],
        minlength: 2,
        maxlength: 5,
        trim: true
    },
    age: {
        type: Number,
        min: 18,
        max: 100
    },
    publishDate: {
        //该字段的类型是时间
        //不为该字段赋值的时候,默认传递当前的时间
        type: Date,
        default: Date.now //默认传递的时间
    }
});
//利用规则创建集合
const Post = mongoose.model('Post', postScheam);

//不传递publishDate
Post.create({ title: 'aa', age: 60 }).then(res => console.log(res))

运行后

打开campass

验证规则之enum

如果传递的值不是规定的值,那么验证失败

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

//创建集合规则
const postScheam = new mongoose.Schema({
    title: {
        type: String,
        required: [true, '请传入文章标题'],
        minlength: 2,
        maxlength: 5,
        trim: true
    },
    age: {
        type: Number,
        min: 18,
        max: 100
    },
    publishDate: {
        //该字段的类型是时间
        //不为该字段赋值的时候,默认传递当前的时间
        type: Date,
        default: Date.now //默认传递的时间
    },
    category: {
        type: String,
        //列举当前字段可以拥有的值
        //如果传入的不是以下字符串,则验证不通过,报错
        enum: ['html', 'css', 'js', 'nodejs']
    }
});
//利用规则创建集合
const Post = mongoose.model('Post', postScheam);

Post.create({ title: 'aa', age: 60, category: 'html' }).then(res => console.log(res))

运行后

自定义验证规则

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

//创建集合规则
const postScheam = new mongoose.Schema({
    title: {
        type: String,
        required: [true, '请传入文章标题'],
        minlength: 2,
        maxlength: 5,
        trim: true
    },
    age: {
        type: Number,
        min: 18,
        max: 100
    },
    publishDate: {
        type: Date,
        default: Date.now //默认传递的时间
    },
    category: {
        type: String,
        enum: ['html', 'css', 'js', 'nodejs']
    },
    author: {
        type: String,
        //validate选项是一个对象
        validate: {
            //validator属性是一个函数
            validator: v => {
                //v就是用户在该字段传入的值,也就是要验证的值,该函数返回布尔值
                //true验证成功,false验证失败

                //如果传了v,且v的长度大于4,那么返回true,插入成功
                return v && v.length > 4
            },
            //自定义错误信息
            message: '传入的值不符合验证规则'
        }
    }
});
//利用规则创建集合
const Post = mongoose.model('Post', postScheam);

Post.create({ title: 'aa', age: 60, category: 'html', author: 'bd' }).then(res => console.log(res))

运行后

提取错误信息

const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/playground', { useNewUrlParser: true })
    .then(() => console.log('数据库连接成功'))
    .catch(err => console.log(err, '数据库连接失败'));

const postScheam = new mongoose.Schema({:
    title: {
        type: String,
        required: [true, '请传入文章标题'],
        minlength: 2,
        maxlength: 5,
        trim: true
    },
    age: {
        type: Number,
        min: 18,
        max: 100
    },
    publishDate: {
        type: Date,
        default: Date.now //默认传递的时间
    },
    category: {
        type: String,
        enum: ['html', 'css', 'js', 'nodejs']
    },
    author: {
        type: String,
        validate: {
            validator: v => {
                return v && v.length > 4
            },
            message: '传入的值不符合验证规则'
        }
    }
});
//利用规则创建集合
const Post = mongoose.model('Post', postScheam);

//提取错误信息
//以下有两个字段不符合规则
Post.create({ title: 'aa', age: 60, category: 'java', author: 'bd' })
    .then(res => console.log(res))
    .catch(err => console.log(err));

运行后

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

//创建集合规则
const postScheam = new mongoose.Schema({
    // title: String,是曾经的写法,如果这样写就指定不了验证规则
    //现在修改写法如下:
    title: {
        type: String,
        required: [true, '请传入文章标题'],
        minlength: 2,
        maxlength: 5,
        trim: true
    },
    age: {
        type: Number,
        min: 18,
        max: 100
    },
    publishDate: {
        type: Date,
        default: Date.now //默认传递的时间
    },
    category: {
        type: String,
        enum: ['html', 'css', 'js', 'nodejs']
    },
    author: {
        type: String,
        validate: {
            validator: v => {
                return v && v.length > 4
            },
            message: '传入的值不符合验证规则'
        }
    }
});
//利用规则创建集合
const Post = mongoose.model('Post', postScheam);

//提取错误信息
//以下有两个字段不符合规则
Post.create({ title: 'aa', age: 60, category: 'java', author: 'bd' })
    .then(res => console.log(res))
    .catch(error => {
        //获取错误信息对象
        const err = error.errors;
        //循环错误信息对象
        for (var attr in err) {
            //将错误信息打印到控制台中
            console.log(err[attr]['message']);

        }
    });


如何为enum自定义错误信息呢?答:不传递数组,改为传递对象。

const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/playground', { useNewUrlParser: true })
    .then(() => console.log('数据库连接成功'))
    .catch(err => console.log(err, '数据库连接失败'));

//创建集合规则
const postScheam = new mongoose.Schema({:
    title: {
        type: String,
        required: [true, '请传入文章标题'],
        minlength: 2,
        maxlength: 5,
        trim: true
    },
    age: {
        type: Number,
        min: 18,
        max: 100
    },
    publishDate: {
        type: Date,
        default: Date.now 
    },
    category: {
        type: String,
        // enum: ['html', 'css', 'js', 'nodejs']

        //自定义错误信息
        enum: {
            values: ['html', 'css', 'js', 'nodejs'],
            message: '分类名称要在一定范围内才可以'
        }
    },
    author: {
        type: String,
        validate: {
            validator: v => {
                return v && v.length > 4
            },
            message: '传入的值不符合验证规则'
        }
    }
});
//利用规则创建集合
const Post = mongoose.model('Post', postScheam);

//提取错误信息
//以下有两个字段不符合规则
Post.create({ title: 'aa', age: 60, category: 'java', author: 'bd' })
    .then(res => console.log(res))
    .catch(error => {
        const err = error.errors;
        for (var attr in err) {
            console.log(err[attr]['message']);
        }
    });

运行后

posted @ 2020-04-03 09:47  deer_cen  阅读(359)  评论(0编辑  收藏  举报