express+mongoDB项目创建及API使用步骤
生活随笔
收集整理的這篇文章主要介紹了
express+mongoDB项目创建及API使用步骤
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
1.根據(jù)express腳手架創(chuàng)建項目
首先確保安裝了express:
npm install express-generator -g //全局安裝創(chuàng)建項目: 創(chuàng)建項目完成后需要使用 npm install 來安裝 npm i mongoose?
express -e 項目名新建module文件夾創(chuàng)建index.js文件:
在創(chuàng)建的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當中創(chuàng)建模型 模型當中有參數(shù) name和flag let a=new mongoose.Schema({name:String,flag:Boolean }) // 在數(shù)據(jù)庫當中創(chuàng)建一個todolist庫,數(shù)據(jù)類型為a let todolist=mongoose.model("todolist",a) // 導出模塊 module.exports =todolist因為exxpress腳手架不存在html頁面 所以需要手動在public中新建html最好使用index.html命名
項目運行:
npm stat運行后在地址欄當中輸入端口號,默認3000可以手動配置
頁面默認為index為根頁面
2.API方法
請求方法主要分post和get請求,如果在請求的時候需要傳遞參數(shù),就是用post傳參,如果只是從數(shù)據(jù)庫取數(shù)據(jù)就用get? 我這里使用jQuery來請求
create 用于在數(shù)據(jù)庫創(chuàng)建一條數(shù)據(jù)
// 添加數(shù)據(jù) router.post("/add", (req, res) => {todolist.create({// 需要的參數(shù)name:req.body.name,flag:req.body.flag}).then(()=>{res.send({code:0})}).catch(()=>{res.send({code:1})}) })find 用于在數(shù)據(jù)庫中查找數(shù)據(jù) 可以選擇是否傳遞數(shù)據(jù) {}代表獲取所有數(shù)據(jù)
// 獲取數(shù)據(jù) 不傳參 router.get("/find",(req,res)=>{todolist.find({}).then((data)=>{res.send({code:0,data:data})}).catch(()=>{res.send({code:404})}) })// 傳遞參數(shù) router.post("/find",(req, res, next) => {// req.body.v是請求傳遞的參數(shù)// 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 用于修改數(shù)據(jù)中的數(shù)據(jù) 通常使用post傳參
// 修改復選框 選中狀態(tài) router.post("/xg",(req,res)=>{// _id是mongodb數(shù)據(jù)庫當中提供的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 用于刪除數(shù)據(jù)庫當中的數(shù)據(jù)
// 刪除數(shù)據(jù) router.post("/del",(req,res)=>{//傳遞id 滿足就刪除todolist.remove({_id:req.body.id}).then(()=>{res.send({code:0})}).catch(()=>{res.send({code:1})}) })總結(jié)
以上是生活随笔為你收集整理的express+mongoDB项目创建及API使用步骤的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 如何阅读Tendermint的日志
- 下一篇: 文件的读写,写入数据,读取数据,写文本