mongoose验证
- 在创建集合规则时, 可以设置当前字段的验证规则, 验证失败则输入插入失败
- required: true 必传字段
- minlength: 3 字符串最小长度
- maxlength: 20 字符串最大长度
- trim: true 去除字符串两边的空格
- min: 2 数值最小为2
- max: 100 数值最大为100
- emun: [‘html’, ‘js’, ‘node.js’]
- validate: 自定义验证器
- default: 默认值
const mongoose = require('mongoose')
mongoose.connect('mongodb://localhost/playground', { useNewUrlParser: 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
},
publishDate: {
type: Date,
default: Date.now
},
category: {
type: String,
enum: {
values: ['html', 'css', 'js', 'node.js'],
message: '分类名称要在一定的范围内才行'
}
},
author: {
type: String,
validate: {
validator: (v) => {
return v && v.length > 4
},
message: '传入的值不符合验证规则'
}
}
})
const Post = mongoose.model('Post', postSchema)
Post.create({title: 'aaa', age: 20, category: 'java', author: 'ss'})
.then(result => console.log(result))
.catch(err => {
const error = err.errors
for (var attr in error) {
console.log(error[attr]['message'])
}
})