This is my code of Router where i imported my cart.js model
var router = require('express').Router();
var Product = require('../models/products');
var Cart = require('../models/cart');
router.get('/add-to-cart/:_id',(req,res,next)=>{
const productID = req.params._id;
var cart = new Cart(req.session.cart ? req.session.cart : {});
Product.findById(productID,(err,product)=>{
if(err){
res.redirect('/');
}
cart.add(product, product.id);
req.session.cart = cart;
res.redirect('/');
})
})
This is My code for Cart.js
module.exports = function cart(oldCart){
this.items = oldCart.items;
this.totalQty = oldCart.totalQty;
this.totalPrice = oldCart.totalPrice;
this.add = function(item,id){
var storedItem = this.items[id]; // Here is Problem
if(!storedItem){
storedItem = this.items[id] = {item: item, qty: 0, price: 0};
}
storedItem.qty++;
storedItem.price = storedItem.item.price * storedItem.qty;
this.totalQty++;
this.totalPrice = storedItem.price;
};
this.generateArray = function(){
var array = [];
for (var id in this.items){
array.push(this.items[id]);
}
return array;
};
}
Error:
events.js:174 throw er; // Unhandled 'error' event ^
TypeError: Cannot read property '5d9182475f539435e81a7bb9' of undefined at cart.add (C:\Users\Manav\Documents\Github\E_com_App\models\cart.js:7:36) at Product.findById (C:\Users\Manav\Documents\Github\E_com_App\routes\routes.js:85:10) at C:\Users\Manav\Documents\Github\E_com_App\node_modules\mongoose\lib\model.js:4589:16 at C:\Users\Manav\Documents\Github\E_com_App\node_modules\mongoose\lib\query.js:4323:12 at process.nextTick (C:\Users\Manav\Documents\Github\E_com_App\node_modules\mongoose\lib\query.js:2805:28) at process._tickCallback (internal/process/next_tick.js:61:11) Emitted 'error' event at: at C:\Users\Manav\Documents\Github\E_com_App\node_modules\mongoose\lib\model.js:4591:13 at C:\Users\Manav\Documents\Github\E_com_App\node_modules\mongoose\lib\query.js:4323:12 at process.nextTick (C:\Users\Manav\Documents\Github\E_com_App\node_modules\mongoose\lib\query.js:2805:28) at process._tickCallback (internal/process/next_tick.js:61:11) [nodemon] app crashed - waiting for file changes before starting...
See my Full code at: https://github.com/ma-9/E_com_NodeJS.git
this.itemsisundefined, which in turn likely means thatoldCartis probably undefined. You need to show what inputs you are expecting, and the usage of the function in context. And please read the link in the comment. Linking to a full and possibly "large enough" listing of code externally goes against what that says. Necessary Code within your question. - Neil Lunn