0
votes

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

3
please go through the SO post on how to ask a question.. - Subburaj
When asking "Why is my code not working" the actual code is pretty much required. Error messages alone tell us little. Please include the smallest necessary code in order to reproduce the problem. Then someone can actually help you. - Neil Lunn
@NeilLunn Thanks for helping me, This is my first experience to StackOverflow - Manav Oza
Needs more context. The error is basically telling you that this.items is undefined, which in turn likely means that oldCart is 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
@NeilLunn Check my Code - Manav Oza

3 Answers

0
votes

i see you code, in this line Product.findById(productID,(err,product)=>{ you call findById function from product module. but i see in this file only

const mongoose = require('mongoose');
const schema = mongoose.Schema;

const productSchema = new schema({
    imagePath: {type: mongoose.Schema.Types.String, required:true},
    // imagePath2: {type: mongoose.Schema.Types.String, required:true},
    // imagePath3: {type: mongoose.Schema.Types.String, required:true},
    // imagePath4: {type: mongoose.Schema.Types.String, required:true},
    // imagePath5: {type: mongoose.Schema.Types.String, required:true},
    name: {type: mongoose.Schema.Types.String, required:true},
    desc: {type: mongoose.Schema.Types.String, required:true},
    price: {type: mongoose.Schema.Types.Number, required:true},
});

module.exports = mongoose.model("DND - Products",productSchema);

You must define the functions you need in this section. EX: findById

0
votes

mongooes db store data with unique id And the key is _id

so edit it

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('/');
})  
})
0
votes

Hello i see your code and i think you have made mistake in Cart.js file and also add-to-cart route.. I have fix the issue and make a pull request to you..

Updated Code

module.exports = function cart(oldCart) {
this.items = oldCart.items || {};
this.totalQty = oldCart.totalQty || 0;
this.totalPrice = oldCart.totalPrice || 0;

this.add = function (item, id) {
    var storedItem = this.items[id];
    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 = (oldCart.totalPrice || 0) + storedItem.price;
};

this.generateArray = function () {
    var array = [];
    for (var id in this.items) {
        array.push(this.items[id]);
    }
    return array;
};

And In Your Routes when you call cart.add(product,product.id) instead of you have to call product._id