Search code examples
node.jsexpressmerndestructor

{ "error": "Cannot destructure property 'title' of 'req.body' as it is undefined." }


following are the code snippets for a Node.js application:

// src/models/workoutsModel.js
const mongoose = require("mongoose");

const Schema = mongoose.Schema;

const workoutSchema = new Schema({
  title: {
    type: String, // Corrected to String
    required: true,
  },
  reps: {
    type: Number,
    required: true,
  },
  load: {
    type: Number,
    required: true,
  },
}, { timestamps: true });

module.exports = mongoose.model("workout", workoutSchema);

// src/Routes/workout.js
const express = require("express");
const Workout = require("../Model/workoutsModel");

const router = express.Router();

router.get("/", (req, res) => {
  res.json({ message: "route for all workouts" });
});

router.get("/:id", (req, res) => {
  res.json({
    message: "getting single routes",
  });
});

router.post("/", async (req, res) => {
  try {
    const { title, reps, load } = req.body;
    const workout = await Workout.create({ title, reps, load });
    res.status(200).json(workout);
  } catch (error) {
    res.status(400).json({ error: error.message });
  }
});

router.delete("/:id", (req, res) => {
  res.json({
    message: "deleting workouts",
  });
});

router.patch("/:id", (req, res) => {
  res.json({
    message: "updating workouts",
  });
});

module.exports = router;

// sr/server.js
require("dotenv").config();
const express = require("express");
const mongoose = require("mongoose");
const workoutRoutes = require("./Routes/workouts");
const app = express();

app.get("/", (req, res) => {
  res.json({ message: "you are on the root page" });
});

app.use((req, res, next) => {
  console.log(req.path, req.method);
  next();
});

app.use("/api/workouts", workoutRoutes);

app.use(express.json());

mongoose
  .connect(process.env.URI)
  .then(() => {
    app.listen(process.env.PORT, () => {
      console.log(
        "connected to the database and listening on port",
        process.env.PORT
      );
    });
  })
  .catch(() => {
    console.log("error connecting to the database");
  }); 

Can anyone please offer me some help here? Currently, I am trying to work with express.json(), but it does not seem to be working as expected when I attempt to destructure the request body. I'm encountering an issue, and I'm unsure how to resolve it. If anyone has experience or insights into using express.json() with destructuring and can provide some guidance or suggestions, I would greatly appreciate it.


Solution

  • Your body parsing middleware is inserted after some of the routes, so those earlier routes won't see any parsed body.

    Make sure your express.json() middleware is installed above your workoutRoutes.