//导入模块
var mongoose = require('mongoose');
//连接数据库
mongoose.connect('mongodb://localhost/itheima');
//创建schema
//schema第一个参数是我们自定义的数据类型 第二个参数是管理schema默认的数据类型
var studentSchema = mongoose.Schema({
name:{type:String,required:true},//数据类型为string,不能非空
age:{type:Number,default:18},//数据类型为string,默认值18
study_id:{type:Number,select:true},//学号,默认查询字段
address:{type:String,lowercase:true},//地址,默认小写
email:{type:String,match:RegExp(/^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(.[a-zA-Z0-9_-])+/)},//邮箱,正则表达式验证
// phone:{type:String,unique:true,dropDups: true}
},{
versionKey: false,//去掉版本锁 __v0
timestamps: { createdAt: 'createTime', updatedAt: 'updateTime' }//自动管理修改时间
});
//创建model
var student = mongoose.model('student',studentSchema);
//创建Entity
var zhangsan = new student({
name:'zhangsan',//名字必须要有,否则会报错: name: Path `name` is required.
address:'ZhongLiang',//字符串都会变成小写
email:'a12345@qq.com',//邮箱格式不对,添加会报错 Path `email` is invalid (a12345qq.com).
study_id:2017001,
// phone:'123456789'
});
//添加数据
student.create(zhangsan,function(err){
if(err){
throw err;
}
console.log('插入成功' + zhangsan);
});
// student.update({name:'zhangsan'},{age:50},function(err,docs){
// if (err) {
// throw err;
// }
// console.log(docs);
// });