full-stack-dev-2023
full-stack-dev-2023 copied to clipboard
Full stack development
Lets fix this and add some description
hi, I am in middle of the course. I am stuck at CURD operation using Schemas and Model (findById). Everything is working well when I am trying to get all the Products , but when Im trying to fecth one product the I am getting the output as "null" . PLease if you solve the issue in the below code. exports.getProduct = async(req,res) =>{ const id = req.params.id; console.log(id); const product = await Product.findById(id).exec(); res.json(product); }
Hi @su340 ,
exports.getProduct= async (req, res) => { const id = +req.params.id; // const id = req.params.id; try { const product = await Product.find({ id: id }); // const product = await Product.findById(id)..exec(); res.status(200).json(product); } catch (err) { res.status(400).json({ message: err.message }); } };
`+`: This is a unary plus operator in JavaScript. When applied to a string, like in +req.params.id, it converts the string to a number. This is used here to ensure that id is treated as a number rather than a string.
So, the overall effect of const id = +req.params.id; is to extract the id parameter from the request URL and convert it to a number, storing it in the variable id. This id can then be used in the Product.find method to query the database for a product with that specific ID.