一、準備工作
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