本文介绍了将产品推送到购物车时遇到错误.类型错误:无法读取未定义的属性“推送"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想在用户点击添加到购物车"时将产品详细信息推送到购物车模型中特定产品上的按钮.但它显示 TypeError: Cannot read property 'push' of undefined
I want to push the product details into the cart model when a user clicks on "add to cart" button on a particular product. But it shows TypeError: Cannot read property 'push' of undefined
这里是路由文件:
var express = require("express"),
router = express.Router(),
Product = require("../models/Product"),
Cart = require("../models/Cart");
router.post("/product/:id/addCart", isLoggedIn, function(req, res){
const quantity = req.body.quantity;
let cart = new Cart();
Product.findById(req.params.id, function(err, foundProduct){
if(err){
console.log(err);
}
const product = {
item: foundProduct._id,
qty: quantity,
price: foundProduct.price * quantity
}
var totalPrice = 0;
totalPrice = totalPrice + product.price;
console.log(req.user._id);
cart.owner = req.user._id;
cart.items.push(product);
cart.totalPrice = totalPrice;
cart.save();
console.log(cart);
res.redirect("/cart");
})
})
这是购物车模型:
var cartSchema = new mongoose.Schema({
owner: {type: mongoose.Schema.Types.ObjectID, ref: 'User'},
items: [{
item: {type: mongoose.Schema.Types.ObjectID, ref: 'Product'},
qty: {type: Number, default: 1},
price: {type: Number, default: 0}
}]
})
module.exports = mongoose.model("Cart", cartSchema);
推荐答案
您在items"中好像有一个错字;收藏.试试
It looks like you have a typo in "items" collection. Try with
Cart.items.push(product);
代替
Cart.itmes.push(product);
这篇关于将产品推送到购物车时遇到错误.类型错误:无法读取未定义的属性“推送"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!