I m sending the id of the product from this view (I m using express and mongoose db)
JavaScript
x
4
1
<form action="/cart" method="POST">
2
<input type="hidden" name="id" value="<%= product._id %>" />
3
<button class="btn" type="submit">Add to Cart</button>
4
I m sure it is not null here
then I have this middleware to receive it
JavaScript
1
2
1
router.post("/cart", shopController.postCart);
2
and here is the function post Cart
JavaScript
1
9
1
exports.postCart = (req, res, next) => {
2
const prodId = req.params.id;
3
console.log("id returned from the params : " + prodId);
4
Product.findById(prodId)
5
.then((product) => {
6
console.log(product);
7
return req.user.addToCart(product);
8
})
9
When I first receive it in the postcard function I made a log and it gives me the log console
JavaScript
1
3
1
id returned from the params: undefined
2
null
3
I tried wrapping the id with ObjectId of mongoose then it shows me this message
JavaScript
1
9
1
exports.postCart = (req, res, next) => {
2
const prodId = req.params.id;
3
console.log("id returned from the params : " + ObjectId(prodId));
4
Product.findById(ObjectId(prodId))
5
.then((product) => {
6
console.log(product);
7
return req.user.addToCart(product);
8
})
9
error :
JavaScript
1
3
1
id returned from the params : 62c9a1ca3b17ea86134d12fc
2
null
3
product: in database :
JavaScript
1
2
1
{ "_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}
2
Advertisement
Answer
Replace const prodId = req.params.id;
with const prodId = req.body.id;
and write
JavaScript
1
2
1
router.post("/cart", express.urlencoded({extended: false}), shopController.postCart);
2
The express.urlcoded
middleware is needed to fill the req.body
.