Skip to content
Advertisement

the id of cart shows null in controller but i m sure i m sending it NODE JS

I m sending the id of the product from this view (I m using express and mongoose db)

    <form action="/cart" method="POST">
      <input type="hidden" name="id" value="<%= product._id %>" />
      <button class="btn" type="submit">Add to Cart</button>

I m sure it is not null here

then I have this middleware to receive it

router.post("/cart", shopController.postCart);

and here is the function post Cart

exports.postCart = (req, res, next) => {
  const prodId = req.params.id;
  console.log("id returned from the params : " + prodId);
  Product.findById(prodId)
    .then((product) => {
      console.log(product);
      return req.user.addToCart(product);
    })

When I first receive it in the postcard function I made a log and it gives me the log console

id returned from the params: undefined
null

I tried wrapping the id with ObjectId of mongoose then it shows me this message

exports.postCart = (req, res, next) => {
  const prodId = req.params.id;
  console.log("id returned from the params : " + ObjectId(prodId));
  Product.findById(ObjectId(prodId))
    .then((product) => {
      console.log(product);
      return req.user.addToCart(product);
    })

error :

id returned from the params : 62c9a1ca3b17ea86134d12fc
null

product: in database :

{  "_id": {    "$oid": "62c87c728594df06fd459521"  },  "title": ",gh,",  "price": 44,  "description": "nfggfngh ",  "imageUrl": "https://media.gettyimages.com/photos/stack-of-books-picture-id157482029?s=612x612",  "userId": {    "$oid": "62c71d0ab0312958a8082d6f"  },  "__v": 0}

Advertisement

Answer

Replace const prodId = req.params.id; with const prodId = req.body.id; and write

router.post("/cart", express.urlencoded({extended: false}), shopController.postCart);

The express.urlcoded middleware is needed to fill the req.body.

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement