zoukankan      html  css  js  c++  java
  • MongoDB 数据验证

    const mongoose = require('mongoose')
    
    mongoose.connect('mongodb://164.red/test', { useUnifiedTopology: true })
        .then(res => console.log('数据库连接成功'))
        .catch(res => console.log('数据库连接失败'))
    
    
    // 定义集合并添加验证规则
    const postSchema = new mongoose.Schema({
        title: {
            type: String,  //类型
            required: [true, '请输入标题'], // 必填
            minlength: [5, '标题长度不能小于5'], // 最小长度
            maxlength: [10, '标题长度不能大于10'], // 最大长度
            trim: true,  // 去除空格
        },
        age: {
            type: Number,
            min: [10, '年龄不能小于10'], // 最小数值
            max: [100, '年龄不能大于100'] // 最大数值
        },
        time: {
            type: Date,
            default: Date.now // 设置默认值
        },
        category: {
            type: String,
            // 枚举当前字段可以拥有的值
            enum: {
                values: ['html', 'css', 'javascript', 'node.js', 'vue', 'react'],
                message: '分类信息不在可选范围'
            }
        },
        author: {
            type: String,
            validate: {
                validator: value => {
                    // 返回布尔值
                    // true验证成功
                    // false验证失败
                    // value要验证的值
                    return value && value.length > 4
                },
                // 返回验证失败的提示信息
                message: '传入的值不符合验证规则'
            }
        }
    })
    
    let data = {
        title: "2333333",
        age: 120,
        time: '',
        category: 'node.js1',
        author: '14'
    }
    
    const Post = mongoose.model('Post', postSchema)
    
    // 处理错误信息
    Post.create(data)
        .then(re => console.log(res))
        .catch(error => {
            let err = error.errors
            if (err) {
                for (let key in err) {
                    console.log(key, err[key].message)
                }
            }
        })
    
  • 相关阅读:
    Java学习之Jdk配置
    Socket网络模型之Select模型
    c#之初见反射
    c++读取文件夹中的文件
    C#泛型的初步理解
    C#接口简单介绍
    c#类,属性,方法和对象基本介绍
    事件的基本认识
    委托的基本认识
    在Xshell中使用rz命令上传文件出现乱码且文件无法删除的解决办法
  • 原文地址:https://www.cnblogs.com/liea/p/12129168.html
Copyright © 2011-2022 走看看