1 const mongoose=require('mongoose') 2 3 mongoose.connect("mongodb://localhost/playground",{ useNewUrlParser: true,useUnifiedTopology: true}) 4 .then(()=>{console.log("数据库连接成功")}) 5 .catch(err=>{console.log(err,'数据库失败')}) 6 const postSchema=new mongoose.Schema({ 7 title:{ 8 type:String, 9 //必选字段 10 required:[true,'请输入字符串'], 11 //最小长度与最大长度 12 minlength:3, 13 maxlength:11, 14 //去除字符串两边空格 15 trim:true 16 }, 17 age:{ 18 type:Number, 19 //数字的最小范围和最大范围 20 min:18, 21 max:100 22 }, 23 publishDate:{ 24 type:Date, 25 //默认值 26 default:Date.now 27 }, 28 category:{ 29 type:String, 30 //列举出当前字段可以拥有哪些值 31 enum:['java','node.js','javascript','zg'] 32 }, 33 author:{ 34 type:String, 35 //自定义验证 36 validate:{ 37 //v是用户输入的值 38 validator:v=>{ 39 //true为验证通过,false为验证失败 40 return v&&v.length>5 41 }, 42 //自定义错误信息 43 message:'传入的值不符合验证规则' 44 45 } 46 } 47 }); 48 const Post=mongoose.model("Post",postSchema); 49 Post.create({title:"zhanggong",age:20,category:"java",author:"rrrr"}).then(res=>{console.log(res)})