学无先后,达者为师

网站首页 编程语言 正文

express 连接 MongoDb

作者:筱闯~ 更新时间: 2023-07-15 编程语言

1.首先 安装 mongoose 插件 创建文件夹

 npm i mongoose
  1. db文件是咱们连接数据库的文件

let mongoose = require("mongoose")
mongoose.connect('mongodb://127.0.0.1:27017/exam') // exam是咱们的数据库名称

const conn = mongoose.connection

conn.on("open",()=>{
    console.log("数据库连接成功");
})

conn.on("error",err=>{
    console.log("失败",err);
})

module.exports = mongoose //暴露

model文件是咱们创建的表

const mongoose = require("./db") 

let Schema = mongoose.Schema
//增加了对数据的校验功能
let studentSchema = new Schema({
    name : {
        type : String,   //name:String
        required : true,  //不能为空
        maxlength : 10 //最大长度
    },
    sex : {
        type : String,
        default : "男" // 默认值
    },
    time : {
        type : Date , 
        default : Date.now() //默认值为当前系统时间
    },
    age : {
        type : Number , 
        max : 150 , //最大值和最小值 限制
        min : 18
    },
    tel : {
        type : String,
        match :  /^1[358]\d{9}$/ // 手机号的校验
    }
},{
    versionKey:false  //去掉自动生成的_v字段
})
//第一个参数和第三个参数最好写成一样的
let studentModel = mongoose.model( "student" , studentSchema , "student" )

//将所有的Model暴露出去
module.exports = {
    studentModel
}

原文链接:https://blog.csdn.net/m0_64544033/article/details/129719222

  • 上一篇:没有了
  • 下一篇:没有了
栏目分类
最近更新