express如何使用MongoDB數(shù)據(jù)庫

一、準備工作

1、要在全局環(huán)境下安裝express以及它的生成器,創(chuàng)建項目,安裝依賴包以及mongoose

2、在啟動項目之前可以修改兩個地方

  • 修改端口號:
    bin/www 文件夾中修改端口號var port = normalizePort(process.env.PORT || '50');
  • 修改后自動啟動項目,這個必須提前在全局安裝好nodemon
    package.json 文件夾中將node改為nodemon:"start": "nodemon ./bin/www"
    5、啟動項目
    npm start

二、使用mongoose連接數(shù)據(jù)庫

1、在項目根目錄下創(chuàng)建lib文件夾,依次創(chuàng)建以下文件,寫入代碼

mongoose.js:用于連接數(shù)據(jù)庫

 //先引入mongoose模塊
 let mongoose = require("mongoose");
 //連接數(shù)據(jù)庫服務(wù)器
 mongoose.connect('mongodb://127.0.0.1:27017/mydb', {
     useNewUrlParser: true,
     useUnifiedTopology: true
 }, function (error) {
     if (error) {
         console.log("數(shù)據(jù)庫連接失敗")
     } else {
         console.log("數(shù)據(jù)庫連接成功")
     }
 })
 //導出
 module.exports = mongoose;

schema.js:用來給數(shù)據(jù)庫的內(nèi)容加限定條件的

 //引入mongoose.js文件
 let mongoose = require("./mongoose.js")
 //定義schema
 let schema = mongoose.Schema
 const blog=new schema({
     //這里是數(shù)據(jù)庫自己創(chuàng)建的屬性名:他的屬性類型   如:
     'name' : {type : String , require : true},
     'age' : {type : Number , require: true},
     'sex' : {type : String, require : true},
     'likes' : {type : String, require : true}
 })
 //導出
 module.exports = blog;

appMode.js:用來定義使用哪個約束條件來約束這個表。

 //引入mongoose.js 文件
 let mongoose = require("./mongoose");
 //引入schema.js 文件
 let schema = require("./schema");
 //定義模型 表名為appModel
 let appModel = mongoose.model("appModel", schema);
 //導出
 module.exports = appModel;
2、然后在router文件夾下的user.js中寫入以下內(nèi)容
let appMode = require('../lib/appMode')
router.post("/add", function (req, res, next) {
  //插入數(shù)據(jù)
  appMode.insertMany([{
    "name": "panda",
    "age": 4,
    "sex": "男",
    "likes": "吃竹子"
  }]).then((data) => {
    console.log('插入成功',data);
  }).catch((err) => {
    console.log('插入失敗');
  });
  res.send("添加成功")
})

由于router.js中的文件已經(jīng)提前在app.js中配置好了路由,因此訪問的時候可以使用localhost:50/users/add


router.png

到這里數(shù)據(jù)庫已經(jīng)連接成功了,可以使用postman去測試一下寫的這個接口是否可用


post.png

查看數(shù)據(jù)庫中的數(shù)據(jù),查看數(shù)據(jù)是否添加成功
sjk.png
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容