The problem is when I make the put request using postman there is an error in my vscode terminal that says:
let product = await Product.findById(req.params.id);
^
TypeError: Cannot read property 'id' of undefined.
I am making this request on postman http://localhost:4500/api/v1/product/61dfc2ba3eb817d287929a7a (61dfc2ba3eb817d287929a7a is the id) with body as raw json. req.params.id is coming to be undefined..
It seemed like an error in parsing so I added body-parser and cors to it but the same error is being showed up..
Code:
const express = require("express");
const mongoose = require("mongoose");
const bodyParser = require("body-parser");
const cors = require("cors");
const app = express();
mongoose
.connect("mongodb://localhost:27017/sampl", {
useNewUrlParser: true,
useUnifiedTopology: true,
})
.then(() => {
console.log("db connected");
})
.catch((err) => {
console.log(err);
});
app.use(express.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.use(cors());
const productSchema = new mongoose.Schema({
name: String,
description: String,
price: Number,
});
const Product = new mongoose.model("Product", productSchema);
//create product
app.post("/api/v1/product/new", async (req, res) => {
const product = await Product.create(req.body);
console.log(req.body);
res.status(200).json({
success: true,
product,
});
});
//read product
app.get("/api/v1/products", async (req, res) => {
const products = await Product.find();
res.status(200).json({
success: true,
products,
});
});
//update product
app.put("/api/v1/product/:id", async (res, req) => {
let product = await Product.findById(req.params.id);
product = await Product.findByIdAndUpdate(req.params.id, req.body, {
new: true,
useFindAndModify: false,
runValidators: true,
});
res.status(200).json({
success: true,
product,
});
});
app.listen(4500, () => {
console.log("server is working");
});
The req object represents the HTTP request and has properties for the request query string, parameters, body, and HTTP headers. The res object represents the HTTP response that an Express app sends when it gets an HTTP request.
So, first we want to pass the req object and then res.
change this
app.put("/api/v1/product/:id", async (res, req) => {
let product = await Product.findById(req.params.id);
to
app.put("/api/v1/product/:id", async (req, res) => {
let product = await Product.findById(req.params.id);