mongodb集合规则

集合规则限定条件

// 第三方模块 操作数据库
let mongoose = require('mongoose');
// 链接数据库
mongoose.connect('mongodb://localhost/school', { useNewUrlParser: true, useUnifiedTopology: true })
    .then(() => {
        console.log('数据库连接成功');
    }).catch(err => console.log(err));

// 1 创建集合规则
const studentSchema = mongoose.Schema({
    name: {
        type: String,
        required: [true, '请传入姓名'], // 必传
        minlength: [2, '姓名长度不能小于2'], // 字符串最小长度
        maxlength: [8, '姓名长度不能大于8'], // 字符串最大长度
        trim: true // 去除字符串首尾空格
    },
    age: {
        type: Number,
        min: 1,
        max: 126
    },
    email: {
        type: String,
        enum: {   // 默认值中选择
            values: ['user@qq.com', 'user@163.com'],
            message: '邮箱地址必须从指定的选择'  // 报错提示信息
        }
    },
    hobbies: [String],
    qq: {
        type: String,
        validate: {
            validator: v => {
                return v.charAt(0) === '1' && v.length === 6;
            },
            message: 'qq号必须以1开头且长度是6'
        }
    },
    birthday: {
        type: Date,
        default: Date.now
    }
});
// 2 创建符合规则的集合实例
const Student = mongoose.model('Student', studentSchema);

Student.create({ name: 'zhangjiejie', qq: '1354678', age: 14, email: 'user@163.com' }).then(res => console.log(res))
    .catch(err => {
        // console.log(err.errors);
    	// 循环显示具体错误信息
        for (var k in err.errors) {
            console.log(err.errors[k].message);
        }
    });
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值