【问题标题】:How to Calculate and return a total cart items in Nodejs and Express如何在 Nodejs 和 Express 中计算并返回购物车物品总数
【发布时间】:2022-01-05 14:54:47
【问题描述】:

我已经在这段代码上反复讨论了一段时间,我试图在购物车对象中有一个 totalQty 值,它返回购物车中的项目总数,我想在视图中使用该值当然就在导航中的购物车图标旁边。这是我的用户模型和路由代码:

用户模型:

const mongoose = require('mongoose');

const Schema = mongoose.Schema;

const userSchema = new Schema({
  role: {
    type: String,
    default: 'BASIC'
  },
  firstName: {
    type: String,
    required: true
  },
  lastName: {
    type: String,
    required: true
  },
  address: {
    type: String
  },
  apartment: {
    type: String
  },
  country: {
    type: String
  },
  state: {
    type: String
  },
  city: {
    type: String
  },
  zip: {
    type: String
  },
  phone: {
    type: String
  },
  email: {
    type: String,
    required: true
  },
  password: {
    type: String,
    required: true
  },
  resetToken: String,
  resetTokenExpiration: Date,
  cart: {
    items: [
      {
        productId: {
          type: Schema.Types.ObjectId,
          ref: 'Product',
          required: true
        },
        quantity: { type: Number, required: true }
      },
    ],
    totalQty: {
      type: Number,
      default: 0
    }
  }
}, { timestamps: true });

userSchema.methods.addToCart = function (product) {
  const cartProductIndex = this.cart.items.findIndex(cp => {
    return cp.productId.toString() === product._id.toString();
  });
  let newQuantity = 1;
  // let newTotalQty = 1;

  const updatedCartItems = [...this.cart.items];

  if (cartProductIndex >= 0) {
    newQuantity = this.cart.items[cartProductIndex].quantity + 1;
    updatedCartItems[cartProductIndex].quantity = newQuantity;

    newTotalQty = this.cart.totalQty + 1;
    updatedTotalQty = newTotalQty;

  } else {
    updatedCartItems.push({
      productId: product._id,
      quantity: newQuantity
    });
  }

  const updatedCart = {
    items: updatedCartItems,
    totalQty: updatedTotalQty

  };
  this.cart = updatedCart;
  return this.save();
};

userSchema.methods.removeFromCart = function (productId) {
  const updatedCartItems = this.cart.items.filter(item => {
    return item.productId.toString() !== productId.toString();
  });
  this.cart.items = updatedCartItems;
  return this.save();
};

userSchema.methods.clearCart = function () {
  this.cart = { items: [] };
  return this.save();
};

module.exports = mongoose.model('User', userSchema);

用户路线:

exports.getCart = (req, res, next) => {
  // populate req user
  req.user
    .populate('cart.items.productId')
    .execPopulate()
    .then(user => {
      const products = user.cart.items;
      // render cart view
      res.render('shop/cart', {
        path: '/cart',
        pageTitle: 'Cart - Hashing365.com',
        products: products
      });
    })
    .catch(err => {
      const error = new Error(err);
      error.httpStatusCode = 500;
      return next(error);
    });
};

exports.postCart = (req, res, next) => {
  // extract prod ID
  const prodId = req.body.productId;
  // run DB find with prod ID
  Product.findById(prodId)
    .then(product => {
      // return true && add to cart
      return req.user.addToCart(product);
    })
    .then(result => {
      // re-render same page
      res.redirect('back');
    })
    .catch(err => {
      const error = new Error(err);
      error.httpStatusCode = 500;
      return next(error);
    });
};

如果有人能帮助我解决这个问题,我将不胜感激。谢谢!

【问题讨论】:

    标签: node.js mongodb ejs


    【解决方案1】:

    您可以查看Array reducer function。它应该是这样的

    cart.totalQty = cart.items.reduce((sum, item)=>{
        return sum + item.quantity;
    },0);
    

    【讨论】:

    • Muhammad,我试过了,但没有成功,所以我尝试在控制台中运行代码示例。发现它只返回 cart.items 数组中最后一项的数量
    • @Rex 请立即查看。它应该是 sum + item.quantity 而不是 item.quantity
    • 谢谢!在您的评论弹出之前,我必须从文档中弄清楚这一点。现在我正在尝试使该返回值在全球范围内可用。除了将其传递给 res.locals 之外,您如何建议这样做?
    • app.use(async (req, res, next) => { res.locals.session = req.session; res.locals.isAuthenticated = req.session.isLoggedIn; res.locals.csrfToken = req.csrfToken(); res.locals.currentUser = req.session.user; next(); });
    • res.locals.session 返回 [Object Object] 与 res.locals.currentUser 相同
    猜你喜欢
    • 1970-01-01
    • 2019-12-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-10
    • 2023-01-12
    • 1970-01-01
    相关资源
    最近更新 更多