{ console.log("连接成功");}).catch(err=>{ console.log("连接失败");})// 创建规则const schema = new mongoose.Schema({ ...">
赞
踩
-
-
- const mongoose = require("mongoose");
-
- // 连接数据库
- mongoose.connect("mongodb://localhost/play",{useNewUrlParser:true})
- .then(res=>{
- console.log("连接成功");
- }).catch(err=>{
- console.log("连接失败");
- })
-
- // 创建规则
- const schema = new mongoose.Schema({
- name:{
- type:String,
- minlength:2,
- maxlength:5
- },
- age:{
- type:Number,
- min:15,
- max:20
- },
- publishDate:{
- type:Date,
- default:Date.now
- },
- category:{
- type:String,
- enum:['html','css','javascript','node.js']
- },
- // 自定义验证规则
- author:{
- type:String,
- // 自定义验证规则
- validate:{
- validator: v => {
- return v && v.length > 4
- },
- message:"莫传入的值不符合验证规则"
- }
- }
- })
- // 通过规则创建集合
- const realyData = mongoose.model("user",schema)
-
- // 往集合里插入文档
- realyData.create({name:"占山",age:16,category:"javascript",author:"aaaaaaa"},(err,res)=>{
- console.log(err);
- console.log(res);
- })
-

Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。