Skip to content
Advertisement

node express mongo API updating a record issue [closed]

i am creating a rest api using node, express, mongoDB. try to make fetch, create, delete , and update functions . all working except update function. when I try to check using postman the code hangs and server stops and errors showing, again when I save the source code the server runs as normal. but every time I try to do the update post the code hangs and error shows up I think something wrong with my update post code, I am beginner in Nodejs , so I am not sure why this error occurs, if anyone knows please check

my crud code is below

import express from "express";
import Post from "../models/PostModel.js";

const router = express.Router();

//  get all posts
router.get("/", async (req, res) => {
  try {
    const posts = await Post.find();
    res.json(posts);
  } catch (err) {
    res.json({ message: err });
  }
});

// submits a post
router.post("/", async (req, res) => {
  const post = new Post({
    title: req.body.title,
    message: req.body.message,
  });
  try {
    const savedPost = await post.save();
    res.json(savedPost);
  } catch (err) {
    res.json({ message: err });
  }
});

// get specific post
router.get("/:postId", async (req, res) => {
  try {
    const post = await Post.findById(req.params.postId);
    res.json(post);
  } catch (err) {
    res.json({ message: err });
  }
});

// delete a specific post
router.delete("/:postId", async (req, res) => {
  try {
    const removePost = await Post.remove({ _id: req.params.postId });
    res.json(removePost);
  } catch (error) {
    res.json({ message: error });
  }
});

//update a post

router.patch("/:postId", async (res, req) => {
  try {
    const updatedPost = await Post.updateOne(
      { _id: req.params.postId },
      { $set: { title: req.body.title } }
    );
    res.json(updatedPost);
  } catch (error) {
    res.json({ message: error });
  }
});

export default router;

this is the error shows up in postman enter image description here


this is the error shows up in vscode once I try to send the patch request in postman

enter image description here

this is the output of get request in postman enter image description here

Advertisement

Answer

The reason is that you have swapped the location of req and res in the .patch request.

Replace the last section of code with the following code. Note it is req, res and not res, req

router.patch("/:postId", async (req, res) => {
  try {
    const updatedPost = await Post.updateOne(
      { _id: req.params.postId },
      { $set: { title: req.body.title } }
    );
    res.json(updatedPost);
  } catch (error) {
    res.json({ message: error });
  }
});
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement