集合规则限定条件
// 第三方模块 操作数据库
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);
}
});