node.js使用mongoose操作數(shù)據(jù)庫(kù)實(shí)現(xiàn)購(gòu)物車(chē)的增、刪、改、查功能示例
本文實(shí)例講述了node.js使用mongoose操作數(shù)據(jù)庫(kù)實(shí)現(xiàn)購(gòu)物車(chē)的增、刪、改、查功能。分享給大家供大家參考,具體如下:
1、數(shù)據(jù)庫(kù)操作語(yǔ)句
Mongoose通過(guò)model實(shí)現(xiàn)對(duì)每個(gè)集合的操作,在使用前需要先定義model:goods。
①、增加數(shù)據(jù):從集合中查詢一條記錄,并返回doc,對(duì)doc操作之后通過(guò)save()保存到集合
goods.findOne({productId},(err,goodsDoc)=>{ goodsDoc.productNum=1; goodsDoc.save(err,doc); });
②、刪除數(shù)據(jù):
model.remove(conditions,callback(){})
③、修改數(shù)據(jù):
model.update(conditions,updates,callback(){})
④、查詢數(shù)據(jù):
model.find(conditions,callback(){})
2、添加購(gòu)物車(chē)
在mongodb中新建用戶user集合,user中有cartList數(shù)組,用戶點(diǎn)擊添加購(gòu)物車(chē)時(shí)在前端發(fā)出post請(qǐng)求包括用戶、商品的id。然后在后端查詢到對(duì)應(yīng)的用戶,將其cartList中的商品id進(jìn)行比對(duì),如果在其中,則把商品數(shù)量+1,否則從商品集合中查詢商品信息,插入到cartList數(shù)組中。
前端添加購(gòu)物車(chē)請(qǐng)求:
addCart(productId){//加入購(gòu)物車(chē) axios.post('./users/addCart',{ userId:"100000077", productId:productId }).then((response)=>{ let res=response.data; console.log(res.msg); }); }
后端處理:
var express = require('express'); var router = express.Router(); const mongoose=require('mongoose'); var user=require('../models/userModel'); var goods=require('../models/productModel'); //連接數(shù)據(jù)庫(kù) mongoose.connect('mongodb://localhost:27017/mall'); mongoose.connection.on('connected',()=>{ console.log("mongoDB連接成功"); }); //處理添加購(gòu)物車(chē)請(qǐng)求 router.post('/addCart',(req,res,next)=>{ let userId=req.body.userId; let productId=req.body.productId; let params={ userId }; user.findOne(params,(err,userDoc)=>{//查詢對(duì)應(yīng)用戶信息 if (err){ res.json({ status:1, msg:err.message }); }else{ if(userDoc){ let inCart=false; userDoc.cartList.forEach(function(item){//遍歷cartList比對(duì)商品id if (item.productId==productId){ //若商品在購(gòu)物車(chē)內(nèi),數(shù)量增加 inCart=true; item.productNum++; saveDoc(userDoc,res); } }); //所選商品不在購(gòu)物車(chē)內(nèi),則從商品列表內(nèi)查找并添加到購(gòu)物車(chē) if(!inCart){ goods.findOne({productId},(err,goodsDoc)=>{ if(err){ res.json({ status:1, msg:err.message }) }else{ goodsDoc.checked=true; goodsDoc.productNum=1; userDoc.cartList.push(goodsDoc);//將商品插入到用戶cartList數(shù)組內(nèi) console.log(userDoc.cartList); saveDoc(userDoc,res); } }); } } } }) });
利用doc.save將修改后的文檔保存到數(shù)據(jù)庫(kù)
function saveDoc(doc,res) { //保存操作 doc.save((err,doc)=>{ if (err){ res.json({ status:1, msg:err.message }) }else { res.json({ status:0, msg:"添加購(gòu)物車(chē)成功", result:'success' }) } }) }
3、從購(gòu)物車(chē)刪除數(shù)據(jù)
前端點(diǎn)擊刪除按鈕,調(diào)用deleteCart()發(fā)出post請(qǐng)求,刪除成功重新加載購(gòu)物車(chē)列表
deleteCart(){ axios.post('users/deleteCart',{ productId:this.productId }).then((response,err)=>{ let res=response.data; if(res.status===0){ this.getCart(); this.modalShow=false; } }) },
后端獲取到刪除商品的id、用戶的id,刪除數(shù)據(jù)庫(kù)中指定條目
router.post('/deleteCart',(req,res)=>{ "use strict"; let productId=req.body.productId; let userId=req.cookies.userId; user.update({userId:userId},{ $pull:{ cartList:{productId:productId} } },(err,doc)=>{ if(err){ res.json({ status:1, msg:'數(shù)據(jù)庫(kù)刪除失敗' }) }else{ if(doc){ res.json({ status:0, msg:'購(gòu)物車(chē)刪除成功' }) } } }) });
4、修改購(gòu)物車(chē)
前端對(duì)不同的按鈕點(diǎn)擊,實(shí)現(xiàn)購(gòu)物車(chē)數(shù)量的增、減、選中的改變,調(diào)用editCart(opt,item),然后將修改的數(shù)據(jù)以post發(fā)送
editCart(flag,item){ if(flag==='check'){ item.checked=!item.checked; }else if(flag==='add'){ item.productNum++; }else if(flag==='sub'){ item.productNum<=0 ? item.productNum=0 : item.productNum++ ; } axios.post('users/editCart',{ productId:item.productId, checked:item.checked, productNum:item.productNum }).then((response,err)=>{ let res=response.data; if(res.status===0){ this.getCart(); }else{ console.log(res.msg); } }) }
后端接收要修改的數(shù)據(jù),并對(duì)數(shù)據(jù)庫(kù)進(jìn)行更新:
router.post('/editCart',(req,res)=>{ "use strict"; let productId=req.body.productId; let checked=req.body.checked; let productNum=req.body.productNum; let userId=req.cookies.userId; user.update({userId:userId,'cartList.productId':productId},{ $set:{"cartList.$.checked":checked,"cartList.$.productNum":productNum} },(err,doc)=>{ if(err){ res.json({ status:1, msg:err.message }) }else { res.json({ status:0, msg:'購(gòu)物車(chē)更新成功' }) } }) });
5、查詢購(gòu)物車(chē)
前端發(fā)送查詢購(gòu)物車(chē)get請(qǐng)求,將結(jié)果數(shù)據(jù)賦予catList,頁(yè)面遍歷cartList渲染數(shù)據(jù)
getCart(){ axios.get('users/getCart').then((response,err)=>{ let res=response.data; if(res.status===0){ this.cartList=res.result.list; }else{ console.log(res.msg); } }) },
后端根據(jù)用戶的cookie,查詢指定的用戶的購(gòu)物車(chē)
router.get('/getCart',(req,res)=>{ "use strict"; user.findOne({userId:req.cookies.userId},(err,doc)=>{ if(doc){ res.json({ status:0, msg:'', result:{ list:doc.cartList } }) }else{ res.json({ status:1, msg:"購(gòu)物車(chē)列表查詢失敗" }) } }) });
6、購(gòu)物車(chē)的總價(jià)與全選
利用vue的計(jì)算屬性可以實(shí)現(xiàn)屬性的隨時(shí)變化,計(jì)算屬性只有在相關(guān)數(shù)據(jù)發(fā)送改變時(shí)才會(huì)隨之改變,計(jì)算屬性的實(shí)現(xiàn)像函數(shù),但使用類(lèi)似于一般屬性,例如總價(jià)totalPrice與判斷是否全部選中allSelected:
computed:{ totalPrice(){ let total=0; this.cartList.forEach((item)=>{ if(item.checked) total+=parseFloat(item.salePrice)*parseInt(item.productNum); }); return total; }, allSelected(){ let selected=true; this.cartList.forEach((item)=>{ selected=selected&&item.checked; }); console.log(selected); return selected; } },
計(jì)算屬性totalPrice由每個(gè)商品單價(jià)*數(shù)量而來(lái),當(dāng)其中有一個(gè)改變時(shí),總價(jià)會(huì)立即改變,顯示在頁(yè)面中。
allSelected由每個(gè)商品是否選中作‘與'運(yùn)算而來(lái),當(dāng)有其中一個(gè)的選中狀態(tài)發(fā)送改變,allSelected也會(huì)改變,并改變購(gòu)物車(chē)的全選標(biāo)志。
希望本文所述對(duì)大家node.js程序設(shè)計(jì)有所幫助。
- node.js連接mongoose數(shù)據(jù)庫(kù)方法詳解
- node.js利用mongoose獲取mongodb數(shù)據(jù)的格式化問(wèn)題詳解
- Node.js+jade+mongodb+mongoose實(shí)現(xiàn)爬蟲(chóng)分離入庫(kù)與生成靜態(tài)文件的方法
- Node.js中使用mongoose操作mongodb數(shù)據(jù)庫(kù)的方法
- Node.js的MongoDB驅(qū)動(dòng)Mongoose基本使用教程
- 安裝使用Mongoose配合Node.js操作MongoDB的基礎(chǔ)教程
- node.js mongoose index索引操作
相關(guān)文章
NodeJs內(nèi)存占用過(guò)高的排查實(shí)戰(zhàn)記錄
這篇文章主要給大家介紹了關(guān)于NodeJs內(nèi)存占用過(guò)高的排查實(shí)戰(zhàn)記錄,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2021-05-05node.js事件輪詢機(jī)制原理知識(shí)點(diǎn)
在本篇文章里小編給大家分享的是一篇關(guān)于node.js事件輪詢機(jī)制的相關(guān)知識(shí)點(diǎn)文章,有興趣的朋友們可以參考下。2019-12-12node制作一個(gè)視頻幀長(zhǎng)圖生成器操作分享
這篇文章主要介紹了node制作一個(gè)視頻幀長(zhǎng)圖生成器操作分享,文章圍繞主題展開(kāi)詳細(xì)的內(nèi)容介紹,具有一定的參考價(jià)值,需要的朋友可以參考一下2022-08-08玩轉(zhuǎn)NODE.JS(四)-搭建簡(jiǎn)單的聊天室的代碼
本篇文章主要介紹了利用NODE.JS搭建簡(jiǎn)單的聊天室的代碼,有需要的可以了解一下。2016-11-11Thinkjs3新手入門(mén)之添加一個(gè)新的頁(yè)面
Thinkjs 是一個(gè)快速、簡(jiǎn)單的基于MVC和面向?qū)ο蟮妮p量級(jí)Node.js開(kāi)發(fā)框架,下面這篇文章主要給大家介紹了關(guān)于Thinkjs3新手入門(mén)之添加一個(gè)新的頁(yè)面的相關(guān)資料,文中通過(guò)示例代碼介紹的非常詳細(xì),需要的朋友可以參考下。2017-12-12Node.js用Socket.IO做聊天軟件的實(shí)現(xiàn)示例
本文主要介紹了Node.js用Socket.IO做聊天軟件的實(shí)現(xiàn)示例,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2022-05-05