protian 2019-06-29
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被去掉文字左右空格
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'