nodejs操作mongodb之五(数据校验)

571 阅读1分钟

一、数据校验的介绍

mysql数据库层面中常见的数据校验,非空字段

二、mongoose中自带的数据校验

  • 1、required表示这个数据必须传入
  • 2、max用于Number类型数据,允许的最大值
  • 3、min用于Number类型数据,允许的最小值
  • 4、enum枚举类型,要去数据必须满足枚举值里面的其中一个
  • 5、match增加数据必须符合match的正则规则
  • 6、maxlength最大长度
  • 7、minlength最小长度

三、在schema中使用数据校验

  • 1、定义schema

    const mongoose = require('./db');
    
    const userSchema = mongoose.Schema({
        name: {
            type: String,
            require: [true, '此项为必填内容'], // 需要自己去写获取其中的错误
            minlength: [3, '名字最小长度为3'],
            maxlength: [10, '名字最长为10'],
        },
        age: {
            type: Number,
            max: 150,
            min: 0,
        },
        status: {
            type: String,
            enum: ['0', '1', '2']
        },
        phone: {
            type: Number,
            match: /^1[3456789]\d{9}$/
        }
    })
    
    module.exports = mongoose.model('User', userSchema, 'user');
    
  • 2、增加数据的时候数据校验

    const UserModel = require('./model/user');
    
    const user = new UserModel({
        name: '李四',
        age: 20,
        status: 3,
        phone: 181706066
    });
    
    user.save((err) => {
        if (err) {
           console.log('-------遍历全部的错误开始---------')
           Object.keys(err.errors).forEach(item => {
               console.log(err.errors[item].message);
           })
           console.log('-------遍历全部的错误结束---------')
        } else {
            console.log('增加数据成功');
        }
    });
    

四、自定义校验器

  • 1、在schema中定义

    const mongoose = require('./db');
    
    const userSchema = mongoose.Schema({
        address: {
            type: String,
            require: true,
            // 方式一:简单定义
            // 自定义的验证器,如果通过验证返回 true,没有通过则返回 false
            // validate: function (desc) {
            //     return desc.length >= 10;
            // },
            // 方式二:需要定义错误提示的方式
            validate: {
                validator: function(desc) {
                    return desc.length >= 10;
                },
                message: '长度必须大于10',
            }
        }
    })
    
    module.exports = mongoose.model('User', userSchema, 'user');
    
  • 2、校验和上面的一样的