egg(27)--mongoose数据校验
连接数据库
db.js
mongodb4.x连接数据库时,要带上{ useNewUrlParser: true }
var mongoose = require('mongoose'); mongoose.connect('mongodb://eggadmin:[email protected]:27017/eggcms',{ useNewUrlParser: true },function(err){ if(err){ console.log(err) return } console.log("数据库连接成功") }) module.exports = mongoose;
required 数据必须传入,用于String,Number
user.js
var mongoose = require('./db.js'); var UserSchema = mongoose.Schema({ name:{ type:String, required:true }, sn:{ type:String, index:true }, age:Number, status:{ type:Number, default:1 } }) var UserModel = mongoose.model('User',UserSchema,'user'); module.exports = UserModel
index.js
var UserModel = require('./user.js'); var user = new UserModel({ // name:'标题3', age:20, sn:"123456" }) user.save(function(err,doc){ if(err){ console.log(err); return; } console.log(doc) })
max,min,用于Number
Number类型数据,最大值和最小值
user.js
age:{ type:Number, min:0, max:150 },
index.js
var user = new UserModel({ name:'标题3', age:166, sn:"123456" }) user.save(function(err,doc){ if(err){ console.log(err); return; } console.log(doc) })
enum枚举类型,要求数据必须满足枚举值,用于String
user.js
status:{ type:String, enum:["success","error"] }
index.js
var user = new UserModel({ name:'标题3', age:16, sn:"123456", status:"success22" }) user.save(function(err,doc){ if(err){ console.log(err); return; } console.log(doc) })
maxlength,minlength,最大和最小长度,用于String
user.js
sn:{ type:String, index:true, maxlength:20, minlength:10 },
index.js
var user = new UserModel({ name:'标题3', age:16, sn:"123456", status:"success" }) user.save(function(err,doc){ if(err){ console.log(err); return; } console.log(doc) })
mathc 正则表达式,用于String
user.js
sn:{ type:String, index:true, match:/^sn(.*)/ //必须以sn开头 },
index.js
var user = new UserModel({ name:'标题3', age:16, sn:"123456", status:"success" }) user.save(function(err,doc){ if(err){ console.log(err); return; } console.log(doc) })
新增sn开头的数据
index.js
var user = new UserModel({ name:'标题3', age:16, sn:"sn123456", status:"success" }) user.save(function(err,doc){ if(err){ console.log(err); return; } console.log(doc) })
validate自定义,true的时候增加数据
自定义的验证器,如果通过验证返回 true,没有通过则返回 false
user.js
sn:{ type:String, index:true, validate:function(desc){ return desc.length >= 10; } },
index.js
var user = new UserModel({ name:'标题3', age:16, sn:"sn123456", status:"success" }) user.save(function(err,doc){ if(err){ console.log(err); return; } console.log(doc) })
传入长度大于10的数据
index.js
var user = new UserModel({ name:'标题3', age:16, sn:"sn123522222456", status:"success" }) user.save(function(err,doc){ if(err){ console.log(err); return; } console.log(doc) })
相关推荐
80530895 2020-07-05
mkhhxxttxs 2020-06-14
80500495 2020-06-14
86211943 2020-03-01
80530895 2020-02-23
80500495 2020-01-29
86211943 2020-01-24
lovecodeblog 2020-01-24
87261046 2019-12-23
86211943 2019-12-20
lightlanguage 2019-12-16
MYRENZHIBO 2019-08-28
85234656 2018-09-03
fudirong 2012-04-12
80500495 2019-07-01