日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網站首頁 編程語言 正文

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

  • 上一篇:沒有了
  • 下一篇:沒有了
欄目分類
最近更新