Search code examples
javascriptreactjsexpresspostman

Delete request not working in Postman for express.js


I have identified the error. However, I do not know why this line of code is causing the error.

 if (!mongoose.Types.ObjectId.isValid(id)) {
  return res.status(404).json({ error: "no such comment" });
 }

when I removed the above lines, the DEL request worked. My new question is, what's wrong with the above lines?

Thank you so, so much.

[Update] The error is that this method is deprecated.


Currently attempting to store comments in Mango DB by using express js as the backend. However, the DEL request is not working when I test it with postman. The server just stops and Postman returns 'Error: read ECONNRESET'.

I asked gpt and it doesn't help either.

Any help appreciated. Thank you so much.

Comment Controller

const Comment = require("../models/Comment");


// delete a comment
const deleteComment = async (req, res) => {
  const {id} = req.params;
  
  if (!mongoose.Types.ObjectId.isValid(id)) {
    return res.status(404).json({ error: "no such comment" });
  }
  try {
    const comment = await Comment.findOneAndDelete({ _id: id });
    if (!comment) {
      return res.status(404).json({ error: "no such comment" });
    }
    res.status(200).json(comment);
  } catch (error) {
    res.status(500).json({ error: "Error deleting comment" });
  }
};

module.exports = {
  createComment,
  getComments,
  deleteComment,
};

Comment Route

const express = require('express');
const {
  createComment, 
  getComments,
  deleteComment,
} = require('../controllers/commentController');

const router = express.Router();


// GET comments for a specific post
router.get('/posts/:id/comments', getComments);

// CREATE a new comment for a specific post
router.post('/posts/:id/comments', createComment);

router.delete('/:id', deleteComment)

module.exports = router;

Server.js

require('dotenv').config()

const express = require('express');
const app = express()
const mongoose = require('mongoose');
const commentsRoute = require('./routes/commentsRoute');
const postsRoute = require('./routes/postsRoute')

// middleware
app.use(express.json())

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

// routes
// mount the comment routes
app.use('/api', commentsRoute);
app.use('/api', postsRoute);

// connect to db
mongoose.connect(process.env.MONGO_URI)
  .then(()=>{
    // listen for requests
    app.listen(process.env.PORT, ()=>{
      console.log('connected to db and listening on port', process.env.PORT)
    })
  })
  .catch((error)=>{
    console.log(error)
  })


Solution

  • Can you try with this?

    // import this
    var ObjectId = require('mongoose').Types.ObjectId;
    
    
    if(!ObjectId.isValid(id)) {
        return res.status(404).json({ error: "no such comment" });
    }