mongoose验证--创建集合对当前字段验证

    技术2023-05-11  104

    //插入数据库模块

    const mongoose = require('mongoose');

     

    //连接数据库

    mongoose.connect('mongodb://localhost/playground', { useNewUrlParse: true })

        .then(result => {

            console.log('数据库连接成功');

        })

        .catch(err => {

            console.log(err, '数据库连接失败');

        })

     

    //创建集合规则

    const postSchema = new mongoose.Schema({

        title: {

            type: String,

            required: [true, '请传入标题'],

            minlength: [2, '文章长度不能小于2'],

            maxlength: [5, '文章长度不能超过5']

        },

        age: {

            type: Number,

            min: 18,

            max: 100

        },

        publishDate: {

            type: Date,

            default: Date.now

        },

        category: {

            type: String,

            /*    enum: {

                 ['html', 'java', 'css', 'javascript']

               } */

            enum: {

                values: ['html', 'java', 'css', 'javascript'],

                message: '分类名称要在一定的范围内才可以'

            }

     

        },

        author: {

            type: String,

            validate: {

                validator: v => {

                    //返回布尔值

                    //true验证成功

                    //false验证失败

                    //v要验证的值

                    return v && v.length > 2

                },

                //自定义错误信息

                message: '传入的值不符合验证规则'

            }

        }

    });

     

    //根据条件创建集合

    const Post = mongoose.model('Post', postSchema);

     

    Post.create({ title: 'aa', age: 30, category: 'jav1', author: 'a' })

        .then(result => console.log(result))

        .catch(error => {

            const err = error.errors;

            for (var attr in err) {

                //将错误信息打印到控制台中

                console.log(err[attr]['message']);

            }

        });

    Processed: 0.015, SQL: 9