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

學(xué)無先后,達(dá)者為師

網(wǎng)站首頁 編程語言 正文

express 連接 MongoDb

作者:筱闖~ 更新時間: 2023-07-15 編程語言

1.首先 安裝 mongoose 插件 創(chuàng)建文件夾

 npm i mongoose
  1. db文件是咱們連接數(shù)據(jù)庫的文件

let mongoose = require("mongoose")
mongoose.connect('mongodb://127.0.0.1:27017/exam') // exam是咱們的數(shù)據(jù)庫名稱

const conn = mongoose.connection

conn.on("open",()=>{
    console.log("數(shù)據(jù)庫連接成功");
})

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

module.exports = mongoose //暴露

model文件是咱們創(chuàng)建的表

const mongoose = require("./db") 

let Schema = mongoose.Schema
//增加了對數(shù)據(jù)的校驗功能
let studentSchema = new Schema({
    name : {
        type : String,   //name:String
        required : true,  //不能為空
        maxlength : 10 //最大長度
    },
    sex : {
        type : String,
        default : "男" // 默認(rèn)值
    },
    time : {
        type : Date , 
        default : Date.now() //默認(rèn)值為當(dāng)前系統(tǒng)時間
    },
    age : {
        type : Number , 
        max : 150 , //最大值和最小值 限制
        min : 18
    },
    tel : {
        type : String,
        match :  /^1[358]\d{9}$/ // 手機(jī)號的校驗
    }
},{
    versionKey:false  //去掉自動生成的_v字段
})
//第一個參數(shù)和第三個參數(shù)最好寫成一樣的
let studentModel = mongoose.model( "student" , studentSchema , "student" )

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

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

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