mongoose+express制作购物车,插入数字时候显示 NaN

发布于 2022-09-07 07:57:17 字数 10544 浏览 34 评论 0

要实现的功能:
1.用户在界面点击“加入购物车”,前端会给一个productId到后台,后台根据productId,在数据库中查询到对应的商品信息,插入到用户表中的cartList中。在插入过程中会添加两个字段:productNum和checked分别表示在购物车中的数量和是否选中商品。
2.在插入用户表之前,要判断该商品是否已经加入过购物车,如果已经加入过,那么只需要把productNum++即可。
问题:
插入cartList之后,productNum在数据库中显示NaN。而且checked也没有插入。

以下是代码

let express   = require('express');
let router    = express.Router();
let mongoose  = require('mongoose');
let Goods     =  require('../models/goods');


//链接数据库
mongoose.connect('mongodb://127.0.0.1:27017/ljcmall');
mongoose.connection.on('connected',()=>{
  console.log('MongoDB connected success!');
});
mongoose.connection.on('error',    ()=>{
  console.log('MongoDB connected fail!');
});
mongoose.connection.on('dis',      ()=>{
  console.log('MongoDB disconnected !');
});

//查询商品列表数据
router.get('/'               , function (req , res , next) {
  let page     = parseInt(req.param('page'));
  let pageSize = parseInt(req.param('pageSize'));
  let sort     = req.param('sort');
  let skip     = (page - 1)*pageSize;
  let params   = {};

  //价格区间定义
  let priceLevel = req.param('priceLevel');
  let priceGt    = '',priceLte = '';
  //价格区间判断
  if (priceLevel !== 'all'){
    switch (priceLevel) {
      case '0' : priceGt = 0    ;priceLte = 100;break;
      case '1' : priceGt = 100  ;priceLte = 500;break;
      case '2' : priceGt = 500  ;priceLte = 1000;break;
      case '3' : priceGt = 1000 ;priceLte = 5000;break;
    }
    params = {
      salePrice:{
        $gt  : priceGt ,
        $lte : priceLte
      }
    }
  }
  let goodsModel = Goods.find(params).skip(skip).limit(pageSize);
  goodsModel.sort({'salePrice':sort});

  goodsModel.exec(function (err, doc)  {
    if(err) {
      res.json({
        status : '1',
        msg : err.message
      });
    }else{
      res.json({
        status : '0',
        msg : '',
        result : {
          count : doc.length ,
          list : doc
        }
      });
    }
  });
});

//加入购物车
router.post("/addCart", function (req,res,next) {
  var userId = '100000077',productId = req.body.productId;
  var User = require('../models/user');
  User.findOne({userId:userId}, function (err,userDoc) {
    if(err){
      res.json({
        status:"1",
        msg:err.message
      })
    }else{
      console.log("userDoc:"+userDoc);
      if(userDoc){
        var goodsItem = '';
        userDoc.cartList.forEach(function (item) {
          if(item.productId == productId){
            goodsItem = item;
            item.productNum ++;
          }
        });
        if(goodsItem){
          userDoc.save(function (err2,doc2) {
            if(err2){
              res.json({
                status:"1",
                msg:err2.message
              })
            }else{
              res.json({
                status:'0',
                msg:'',
                result:'suc'
              })
            }
          })
        }else{
          Goods.findOne({productId:productId}, function (err1,doc) {
            if(err1){
              res.json({
                status:"1",
                msg:err1.message
              })
            }else{
              if(doc){
                doc.productNum = 1;
                doc.checked = 1;
                userDoc.cartList.push(doc);
                userDoc.save(function (err2,doc2) {
                  if(err2){
                    res.json({
                      status:"1",
                      msg:err2.message
                    })
                  }else{
                    res.json({
                      status:'0',
                      msg:'',
                      result:'suc'
                    })
                  }
                })
              }
            }
          });
        }
      }
    }
  })
});
module.exports = router;
let mongoose   = require('mongoose');
let userSchema =  new mongoose.Schema({//定义的时候要跟数据库严格相等
  'userId'      : String ,
  'userName'    : String ,
  'userPwd'     : String ,
  'orderList'   : Array  ,
  'cartList'    : [{
    'productId'    : String ,
    'productName'  : String ,
    'salePrice'    : String ,
    'productImage' : String ,
    'checked'      : String ,
    'productNum'   : String
  }],
  'addressList' : Array
});

module.exports = mongoose.model('User',userSchema,'users');//如果不加第三个参数 数据库会用第一个参数加上's'在数据库中查找集合
<template>
  <div>
    <nav-header></nav-header>
    <nav-bread></nav-bread>
    <div class="accessory-result-page accessory-page">
      <div class="container">
        <div class="filter-nav">
          <span class="sortby">Sort by:</span>
          <a href="javascript:void(0)" class="default cur">Default</a>
          <a @click="sortGoods" href="javascript:;" class="price">Prices</a>
          <a href="javascript:void(0)" class="filterby stopPop" @click="showFilterPop">Filter by</a>
        </div>
        <div class="accessory-result">
          <!-- filter -->
          <div class="filter stopPop" id="filter" :class="{'filterby-show': filterBy}">
            <dl class="filter-price">
              <dt>Price:</dt>
              <dd><a href="javascript:void(0)" :class="{'cur': priceChecked==='all'}" @click="turnAll">All</a></dd>
              <dd v-for="(price, index) in priceFilter" @click="setPriceFilter(index)">
                <a href="javascript:void(0)" :class="{'cur':priceChecked === index}">{{price.startPrice}} - {{price.endPrice}}</a>
              </dd>
            </dl>
          </div>

          <!-- search result accessories list -->
          <div class="accessory-list-wrap">
            <div class="accessory-list col-4">
              <ul>
                <li v-for="(item,index) in goodsList">
                  <div class="pic">
                    <a href="#"><img v-lazy="'/static/'+item.productImage" alt=""></a>
                  </div>
                  <div class="main">
                    <div class="name">{{item.productName}}</div>
                    <div class="price">{{item.salePrice}}</div>
                    <div class="btn-area">
                      <a href="javascript:;" class="btn btn--m" @click="addCart(item.productId)">加入购物车</a>
                    </div>
                  </div>
                </li>
              </ul>
              <div v-infinite-scroll="loadMore" infinite-scroll-disabled="busy" infinite-scroll-distance="20">
                <img src="./../assets/img/loading-spinning-bubbles.svg" v-show="loading">
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
    <div class="md-overlay" v-show="overLayFlag" @click="closePop"></div>
    <nav-footer></nav-footer>
  </div>
</template>

<script>
  import NavHeader from '@/components/NavHeader' ;
  import NavFooter from '@/components/NavFooter' ;
  import NavBread  from '@/components/NavBread'  ;
  import axios     from 'axios'                  ;

  export default {
    name       : 'goods-list'        ,
    data       : function () {
      return{
        goodsList: [],
        priceFilter: [
          {
            startPrice: '00.00',
            endPrice: '100.00'
          },
          {
            startPrice: '100.00',
            endPrice: '500.00'
          },
          {
            startPrice: '500.00',
            endPrice: '1000.00'
          },
          {
            startPrice: '1000.00',
            endPrice: '5000.00'
          },
        ],
        priceChecked: 'all',
        filterBy: false,
        overLayFlag: false,
        //分页
        sortFlag : true,
        page : 1 ,
        pageSize : 8,
        //加载
        busy : true,
        loading: false
      }
    }   ,
    mounted    : function () {
      this.getGoodsList();
    }   ,
    methods    : {
      getGoodsList   (flag) {
        let param = {
          page : this.page ,
          pageSize : this.pageSize ,
          sort : this.sortFlag?1:-1 ,
          priceLevel : this.priceChecked
        };
        this.loading = true;
        axios.get('/goods',{
          params : param
        }).then((response)=>{
          this.loading = false;
          let res = response.data;
          if(res.status === '0'){
            if(flag){
              //叠加分页
              this.goodsList = this.goodsList.concat(res.result.list);
              if (res.result.count === '0') {
                this.busy = true;
              }else {
                this.busy = false;
              }
            }else{
              this.goodsList = res.result.list;
              this.busy = false;
            }
          }else {
            this.goodsList = [];
          }
        }).catch((error)=>{
          console.log(error)
        });
      }  ,
      sortGoods      () {
        this.sortFlag =!this.sortFlag;
        this.page = 1;
        this.getGoodsList();
      }      ,
      setPriceFilter (index) {
        this.priceChecked = index ;
        this.page         = 1     ;
        this.closePop()           ;
        this.getGoodsList()       ;
        // console.log(this.priceChecked);
      } ,
      turnAll        () {
        this.priceChecked = 'all';
        this.closePop();
        this.getGoodsList();
      }      ,
      showFilterPop  () {
        this.filterBy = true ;
        this.overLayFlag = true;
      }      ,
      closePop       () {
        this.filterBy = false ;
        this.overLayFlag = false;
      }      ,
      loadMore       () { //为了防止鼠标滚动过快,请求加载过于频繁
        this.busy = true ;
        setTimeout( () => {
          this.page++;
          this.getGoodsList(true);
        },500)
      }      ,
      addCart        (productId) {
        axios.post ('/goods/addCart' , {
          productId
        }).then((res) => {
          console.log(res);
          if (res.data.status === '0') {
              alert('加入成功')
          }else {
              alert('msg : ' + res);
              console.log(res);
          }
        })
      }
    },
    components : {
      NavHeader ,
      NavFooter ,
      NavBread
    },
  }
</script>

<style scoped>

</style>

还希望大神不吝指教!非常感谢!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

迎风吟唱 2022-09-14 07:57:17

照你所说productNum的类型不应该是Number吗

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文