egg(25)--mongoose预定义模式修饰符 Getters与 Setters修饰符
预定义模式修饰符
news.js
给title增加一个trim,去掉文字左右空格的内部修饰符
var mongoose = require('./db.js'); var NewsSchema = mongoose.Schema({ title:{ type:String, trim:true }, content:String }) //定义model操作数据库 // var UserModel = mongoose.model('User',UserSchema); //将生成users表 var NewsSchema = mongoose.model('news',NewsSchema,'news'); module.exports = NewsSchema
index.js
var UserModel = require('./user.js'); var NewsSchema = require('./news.js'); var news = new NewsSchema({ title:' 标题1 ', content:'内容1', }) news.save(function(err,doc){ if(err){ console.log(err); return; } console.log(doc) })
运行发现,存入数据库的title被去掉文字左右空格
自定义Getters与 Setters修饰符
set是数据在存入的时候做处理
get是数据在拿出的时候做处理,一般不用
news.js
var mongoose = require('./db.js'); var NewsSchema = mongoose.Schema({ title:{ type:String, trim:true }, content:String, url:{ type:String, set(params){ if(!params){ return '' }else{ if(params.indexOf('http://') !=0 && params.indexOf('https://') !=0){ return 'http://' + params; } return params; } } } }) var NewsSchema = mongoose.model('news',NewsSchema,'news'); module.exports = NewsSchema
index.js
存入url:'www.baidu.com'
var UserModel = require('./user.js'); var NewsSchema = require('./news.js'); var news = new NewsSchema({ title:'标题2', content:'内容1', url:'www.baidu.com' }) news.save(function(err,doc){ if(err){ console.log(err); return; } console.log(doc) })
运行后,自动加上了http://
如果直接存入url:'http://www.baidu.com'
相关推荐
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