user12674982
user12674982

Reputation:

Node.js:"Cannot read property 'toString' of undefined

I'm following a restApi course with Node.js, It's a blog API. my problem is when deleting a post for the unAuthorized user it first gives me a 500 error

"error": "Cannot read property 'toString' of undefined"

. but when doing it again it gives me

Post not found with id of.

Of course, it supposed to give me

not authorized to delete this post.

Update the post is also the same, I even tried to copy/paste the code from the course but the same problem.

postController

exports.deletePost = asyncHandler(async (req, res, next) => {
    const post = await Post.findByIdAndDelete(req.params.id); 
    if (!post) {
      return next(
        new ErrorResponse(`Post not found with id of ${req.params.id}`, 404)
      );
    }
    // Make sure user is post owner
  if (post.user.toString() !== req.user.id) {
    return next(
      new ErrorResponse(
        `User ${req.params.id} is not authorized to delete this post`,
        401
      )
    );
  }
  post.remove();

    res.status(200).json({ success: true, data: post});

});

updatePost

exports.updatePost = asyncHandler(async (req, res, next) => {
    let post = await Post.findById(req.params.id);
  
    if (!post) {
      return next(
        new ErrorResponse(`Post not found with id of ${req.params.id}`, 404)
      );
    }

  // Make sure user is post owner
  if (post.user.toString() !== req.user.id) {
    return next(
      new ErrorResponse(
        `User ${req.params.id} is not authorized to update this post`,
        401
      )
    );
  }

  post = await Post.findOneAndUpdate(req.params.id, req.body, {
    new: true,
    runValidators: true
  });

  res.status(200).json({ success: true, data: post });
});

Upvotes: 1

Views: 4064

Answers (3)

Hetal Malaviya
Hetal Malaviya

Reputation: 1

const express = require("express");
const router = express.Router();
const fetchuser = require("../middleware/Fetchuser");
const Notes = require("../models/Notes.js");
const { body, validationResult } = require("express-validator");

router.get("/fetchnotes", fetchuser, async (req, res) => {
  try {
    const notes = await Notes.find({ user: req.user });

    res.json(notes);
  } catch (error) {
    console.log(error.message);
    res.status(500).send("error occured");
  }
});

router.post(
  "/addnotes",
  [
    body("title").isLength({ min: 5 }),
    body("description").isLength({ min: 3 }),
  ],
  fetchuser,
  async (req, res) => {
    try {
      const { title, description, tag } = req.body;

      const errors = validationResult(req);
      if (!errors.isEmpty()) {
        return res.status(400).json({ errors: errors.array() });
      }

      const note = new Notes({
        title,
        description,
        tag,
        user: req.user.id,
      });
      const savedNotes = await note.save();

      res.json(savedNotes);
    } catch (error) {
      console.log(error.message);
      res.status(500).send("error occured");
    }
  }
);
router.put("/updatenotes/:id", fetchuser, async (req, res) => {
  const { title, description, tag } = req.body;
  const newNote = {};
  if (title) {
    newNote.title = title;
  }
  if (description) {
    newNote.description = description;
  }
  if (tag) {
    newNote.tag = tag;
  }

  let note = await Notes.findById(req.params.id);
  if (!note) {
    return res.status(400).send("error occured");
  }

  if (note.user !== req.user.id.parseInt) {
    return res.status(401).json("user not allowed");
  }

  note = await Notes.findByIdAndUpdate(
    req.params.id,
    { $set: newNote },
    { new: true }
  );
  res.json(note);
});
module.exports = router;

Upvotes: 0

Malindu Sasanga
Malindu Sasanga

Reputation: 325

I have tried the code if (typeof post.user == "undefined" || post.user.toString() !== req.user.id)

But after using this cause to get me an error 'User not Authorized' in my error handling.

In my case, I have to convert the req.user.id to an integer

if (post.user !== req.user.id.parseInt)

Upvotes: 0

Shaun Miah
Shaun Miah

Reputation: 26

You could introduce a type check on the post.user object to ensure that the user exists within the post.

if (typeof post.user == "undefined" || post.user.toString() !== req.user.id)

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/typeof

Upvotes: 1

Related Questions