zoukankan      html  css  js  c++  java
  • 验证规则 以及错误信息处理

    // 引入 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']);
            }
        })
  • 相关阅读:
    如果使用Excel oledb 导数据出现各种错误的解决方法
    如何对给定序列进行趋势预测
    Winform自定义控件之二叉树控件(2)
    WinForm自定义控件开发(1)
    .net 3.5 中的 服务器端回调
    Python内存管理
    oracle to mysql hibernate 实体id生成策略配置
    oracle to mysql
    mysql 删除所有表
    oracle函数在mysql用
  • 原文地址:https://www.cnblogs.com/ericblog1992/p/13088679.html
Copyright © 2011-2022 走看看