express+mongoDB项目创建及API使用步骤
生活随笔
收集整理的這篇文章主要介紹了
express+mongoDB项目创建及API使用步骤
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
1.根據express腳手架創建項目
首先確保安裝了express:
npm install express-generator -g //全局安裝創建項目: 創建項目完成后需要使用 npm install 來安裝 npm i mongoose?
express -e 項目名新建module文件夾創建index.js文件:
在創建的module index.js中加入以下代碼與服務器建立鏈接
// 引入mongoose const mongoose = require("mongoose"); // 讓mongoose和mongodb進行鏈接 //localhost:27017代表端口號 mongoose.connect("mongodb://localhost:27017").then(res=>{// 成功會在終端當中打印console.log("鏈接成功"); }).catch(res=>{console.log("連接失敗"); }) // 在mongoose當中創建模型 模型當中有參數 name和flag let a=new mongoose.Schema({name:String,flag:Boolean }) // 在數據庫當中創建一個todolist庫,數據類型為a let todolist=mongoose.model("todolist",a) // 導出模塊 module.exports =todolist因為exxpress腳手架不存在html頁面 所以需要手動在public中新建html最好使用index.html命名
項目運行:
npm stat運行后在地址欄當中輸入端口號,默認3000可以手動配置
頁面默認為index為根頁面
2.API方法
請求方法主要分post和get請求,如果在請求的時候需要傳遞參數,就是用post傳參,如果只是從數據庫取數據就用get? 我這里使用jQuery來請求
create 用于在數據庫創建一條數據
// 添加數據 router.post("/add", (req, res) => {todolist.create({// 需要的參數name:req.body.name,flag:req.body.flag}).then(()=>{res.send({code:0})}).catch(()=>{res.send({code:1})}) })find 用于在數據庫中查找數據 可以選擇是否傳遞數據 {}代表獲取所有數據
// 獲取數據 不傳參 router.get("/find",(req,res)=>{todolist.find({}).then((data)=>{res.send({code:0,data:data})}).catch(()=>{res.send({code:404})}) })// 傳遞參數 router.post("/find",(req, res, next) => {// req.body.v是請求傳遞的參數// new RegExp 是正則表達式的縮寫 "g"代表全局標志var reg=new RegExp(req.body.v,"g")book.find({mc:reg}).then((data) => {res.send({code:1,data:data})}).catch(()=>{res.send({code:0})}) })update 用于修改數據中的數據 通常使用post傳參
// 修改復選框 選中狀態 router.post("/xg",(req,res)=>{// _id是mongodb數據庫當中提供的id flag需要手動設置todolist.update({_id:req.body.id},{flag:true}).then(()=>{res.send({code:0})}).catch(()=>{res.send({code:1})}) }) // 修改復選框 取消選中 router.post("/emit",(req,res)=>{todolist.update({_id:req.body.id},{flag:false}).then(()=>{res.send({code:0})}).catch(()=>{res.send({code:1})}) })remove 用于刪除數據庫當中的數據
// 刪除數據 router.post("/del",(req,res)=>{//傳遞id 滿足就刪除todolist.remove({_id:req.body.id}).then(()=>{res.send({code:0})}).catch(()=>{res.send({code:1})}) })總結
以上是生活随笔為你收集整理的express+mongoDB项目创建及API使用步骤的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 如何阅读Tendermint的日志
- 下一篇: web前端开发-html5基础(含代码)