Caught an error while pushing a product to cart. TypeError: Cannot read property 'push' of undefined

假装没事ソ 提交于 2020-12-15 05:37:34

问题


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

Here is the route file:

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");
})  
})

This is the cart model:

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);

回答1:


It looks like you have a typo in "items" collection. Try with

Cart.items.push(product);

instead

Cart.itmes.push(product);



来源:https://stackoverflow.com/questions/64388457/caught-an-error-while-pushing-a-product-to-cart-typeerror-cannot-read-property

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!