前端学习(1342):mongoose验证规则拿到错误信息
生活随笔
收集整理的這篇文章主要介紹了
前端学习(1342):mongoose验证规则拿到错误信息
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/playground', { useUnifiedTopology: true }).then(() => console.log('數(shù)據(jù)庫連接成功')).catch(err => console.log(err, '數(shù)據(jù)庫連接失敗'))//創(chuàng)建集合規(guī)則
const postSchema = new mongoose.Schema({title: {type: String,require: [true, '請傳入文章標(biāo)題'],minlength: [2, '輸入長度不能小于2'],maxlength: [5, '輸入長度不能大于5'],const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/playground', { useUnifiedTopology: true }).then(() => console.log('數(shù)據(jù)庫連接成功')).catch(err => console.log(err, '數(shù)據(jù)庫連接失敗'))//創(chuàng)建集合規(guī)則
const postSchema = new mongoose.Schema({title: {type: String,require: [true, '請傳入文章標(biāo)題'],minlength: [2, '輸入長度不能小于2'],maxlength: [5, '輸入長度不能大于5'],//不允許有空格trim: true},age: {type: Number,//數(shù)字得最小范圍min: 18,//數(shù)字得最大范圍max: 100},publishDate: {type: Date,default: Date.now},category: {type: String,enum: {values: ['html', 'css', 'javascript'],message: '傳入得不符合規(guī)則'},},author: {type: String,validate: {validator: v => {//true 驗證成功//false驗證失敗v.length>4return v && v.length > 4},//自定義錯誤信息message: '傳入得值不符合規(guī)則'}}
});
const Post = mongoose.model('Post', postSchema);
//插入數(shù)據(jù)
Post.create({ title: 'aa', age: 60, category: 'java', author: '125' }).then(result => console.log(result)).catch(error => {//獲取錯誤信息對象const err = error.errors;//循環(huán)錯誤對象for (var attr in err) {console.log(err[attr]['message'])}});//不允許有空格trim: true},age: {type: Number,//數(shù)字得最小范圍min: 18,//數(shù)字得最大范圍max: 100},publishDate: {type: Date,default: Date.now},category: {type: String,enum: ['html', 'css', 'javascript']},author: {type: String,validate: {validator: v => {//true 驗證成功//false驗證失敗v.length>4return v && v.length > 4},//自定義錯誤信息message: '傳入得值不符合規(guī)則'}}
});
const Post = mongoose.model('Post', postSchema);
//插入數(shù)據(jù)
Post.create({ title: 'aa', age: 60, category: 'java', author: '125' }).then(result => console.log(result)).catch(err => {//獲取錯誤信息對象const err = err.errors;//循環(huán)錯誤對象for (var attr in arr) {console.log(err[attr]['message'])}});
運行結(jié)果
總結(jié)
以上是生活随笔為你收集整理的前端学习(1342):mongoose验证规则拿到错误信息的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 一文详解高精地图构建与SLAM感知优化建
- 下一篇: 网络安全资料汇总!