Mohd Akram
Mohd Akram

Reputation: 83

i can not fetch data to another page using mongo atlas in node.js always show error message cannot read property of function

Error

TypeError: Cannot read property 'map' of undefined
    at User.getCart (D:\udamNode\models\user.js:49:40)
    at exports.getCart (D:\udamNode\controllers\shop.js:55:6)
    at Layer.handle [as handle_request] (D:\udamNode\node_modules\express\lib\router\layer.js:95:5)
    at next (D:\udamNode\node_modules\express\lib\router\route.js:137:13)
    at Route.dispatch (D:\udamNode\node_modules\express\lib\router\route.js:112:3)
    at Layer.handle [as handle_request] (D:\udamNode\node_modules\express\lib\router\layer.js:95:5)
    at D:\udamNode\node_modules\express\lib\router\index.js:281:22
    at Function.process_params (D:\udamNode\node_modules\express\lib\router\index.js:335:12)
    at next (D:\udamNode\node_modules\express\lib\router\index.js:275:10)
    at Function.handle (D:\udamNode\node_modules\express\lib\router\index.js:174:3)

Model file method

getCart() {
const db = getDb();
const productIds = this.cart.items.map(i => {
  return i.productId;
});
return db.collection('products').find({ _id: { $in: productIds } }).toArray().then(products => {
    return products.map(p => {
      return {
        ...p,
        quantity: this.cart.items.find(i => {
          return i.productId.toString() === p._id.toString();
        }).quantity
      };
    });
  });

}

Controller file method

exports.getCart = (req, res, next) => {req.user.getCart().then(products => {
  res.render('shop/cart', {
    path: '/cart',
    pageTitle: 'Your Cart',
    products: products
  });
}).catch(err => console.log(err));

};

Upvotes: 1

Views: 37

Answers (1)

Andrei Piatrou
Andrei Piatrou

Reputation: 434

In code provided above this.cart.items is undefined. this mean that when user is fetched the result object does not include cart.items in the query result payload.

So in case of mongodb one of the following ways should help:

  1. items nested models have to be included when user is queried from the DB
  2. cart with its items should be queried with an additional query in getCart() method first.

Upvotes: 1

Related Questions