protian 2019-06-29
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;
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) })
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) })
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) })
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) })
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) })
自定义的验证器,如果通过验证返回 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) })