I'm Having a TypeError on NodeJS for POST method on MongoDB: Cannot read properties of undefined (reading 'name')

Issue

I know this question has been asked a lot of times but the majority of them is for frameworks or other tech stacks, I’m using NodeJS with Express and a database on MongoDB and I’m testing my API with Postman. When I try to send the request to the API on POST return the next message (ON the app, Postman just sends: Could not get response):

addProductsCart.js:21
_req$body = req.body, name = _req$body.name, description = _req$body.description, image = _req$body.image, price = _req$body.price, productType = _req$body.productType;
^
TypeError: Cannot read properties of undefined (reading ‘name’)

going to the file that the error sends it seems like there’s nothing wrong

import Product from '../models/Products';
import Cart from '../models/Cart';


const addProductCart = async (req, res) => {

    const {name, description, image, price, productType} = req.body;
    

    const estaEnProducts = await Product.findOne({name});
  

    const noEstaVacio = name !== "" && description !== "" && image !== "" && price !== "" && productType !== "";
  

    const estaEnElCarrito = await Cart.findOne({name});
  

    if (!estaEnProducts) {
      res.status(400).json({
        mensaje: "This products is not in our DataBase",
      });
  
    } else if (noEstaVacio && !estaEnElCarrito) {
      const newProductInCart = new Cart({name, description, image, price, productType, amount: 1 });
  
      /* Update the property of inCart */
      await Product.findByIdAndUpdate(
        estaEnProducts?._id,
        { inCart: true, name, description, image, price, productType },
        { new: true }
      )
        .then((product) => {
          newProductInCart.save();
          res.json({
            mensaje: `Product added correctly`,
            product,
          });
        })
        .catch((error) => console.error(error));
  
      /* Validate if product is already in cart */
    } else if (estaEnElCarrito) {
      res.status(400).json({
        mensaje: "Product already in cart",
      });
    }
  };
  
  module.exports = addProductCart;

in my models i’m using the exact same names for the controllers:

import {Schema, model} from 'mongoose';

const cartSchema = new Schema({
    name: {type: String, required: true, unique: true},
    description: {type: String, required: true},
    image: {type: String, required: true, unique: true},
    price: {type: Number, required: true},
    productType: {type: String, required: false},
    amount: {type: Number, required: true},
});

export default model('Cart',cartSchema);

and this is the product model:

import {Schema, model} from 'mongoose';

const productsSchema = new Schema({
    name: {type: String, required: true, unique: true},
    description: {type: String, required: true},
    image: {type: String, required: true, unique: true},
    inCart: {type: Boolean, default: false},
    price: {type: Number, required: true},
    productType: {type: String, required: false},
});

export default model('Products',productsSchema);

I’m using Import instead of require with Babel so there’s no problem there

I’m not able to found the error there, also I think I’m doing the petition correclty on Postman (Using the next JSON, that is a product created before on DB and telling Postman on headers that the Content-type is application/json)

{
    "name": "producto-test",
    "description": "descripcion de prueba",
    "image": "https://cdn.betterttv.net/emote/58ae8407ff7b7276f8e594f2/3x",
    "price": 100000,
    "productType": "Camara"
}

If someone knows what I’m doing wrong I’ll really apreciate that, finally I let all the log of the error, if may be helpful

TypeError: Cannot read properties of undefined (reading 'name')
    at _callee$ (C:\AltoVoltajeFilms\src\controllers\/addProductsCart.js:7:12)
    at tryCatch (C:\AltoVoltajeFilms\node_modules\regenerator-runtime\runtime.js:63:40)
    at Generator.invoke [as _invoke] (C:\AltoVoltajeFilms\node_modules\regenerator-runtime\runtime.js:294:22)
    at Generator.next (C:\AltoVoltajeFilms\node_modules\regenerator-runtime\runtime.js:119:21)
    at asyncGeneratorStep (C:\AltoVoltajeFilms\src\controllers\addProductsCart.js:9:103)
    at _next (C:\AltoVoltajeFilms\src\controllers\addProductsCart.js:11:194)
    at C:\AltoVoltajeFilms\src\controllers\addProductsCart.js:11:364
    at new Promise (<anonymous>)
    at C:\AltoVoltajeFilms\src\controllers\addProductsCart.js:11:97
    at addProductCart (C:\AltoVoltajeFilms\src\controllers\/addProductsCart.js:5:21)

Solution

req.body is undefined. Did you add json() to your express app?
If not add it

const app = express()
app.use(express.json())

Answered By – Phạm Vỹ

Answer Checked By – Clifford M. (AngularFixing Volunteer)

Leave a Reply

Your email address will not be published.