skip to Main Content

I’m working on a social media project and getting this getting when I’m sending like/Unlike post request

CastError: Cast to ObjectId failed for value "6283n" (type string) at path "_id" for model "Post"
at model.Query.exec (E:social-media-app-mernnode_modulesmongooselibquery.js:4639:21)
at model.Query.Query.then (E:social-media-app-mernnode_modulesmongooselibquery.js:4738:15)
at processTicksAndRejections (node:internal/process/task_queues:96:5) {
messageFormat: undefined,
stringValue: ‘"6283n"’,
kind: ‘ObjectId’,
value: ‘6283n’,
path: ‘_id’,
reason: BSONTypeError: Argument passed in must be a string of 12 bytes or a string of
24 hex characters or an integer
at new BSONTypeError (E:social-media-app-mernnode_modulesbsonliberror.js:41:28)
at new ObjectId (E:social-media-app-mernnode_modulesbsonlibobjectid.js:66:23) at castObjectId (E:social-media-app-mernnode_modulesmongooselibcastobjectid.js:25:12)
at ObjectId.cast (E:social-media-app-mernnode_modulesmongooselibschemaobjectid.js:247:12)
at ObjectId.SchemaType.applySetters (E:social-media-app-mernnode_modulesmongooselibschematype.js:1135:12)
at ObjectId.SchemaType._castForQuery (E:social-media-app-mernnode_modulesmongooselibschematype.js:1567:15)
at ObjectId.SchemaType.castForQuery (E:social-media-app-mernnode_modulesmongooselibschematype.js:1557:15)
at ObjectId.SchemaType.castForQueryWrapper (E:social-media-app-mernnode_modulesmongooselibschematype.js:1534:20)
at cast (E:social-media-app-mernnode_modulesmongooselibcast.js:336:32)
at model.Query.Query.cast (E:social-media-app-mernnode_modulesmongooselibquery.js:5062:12),
valueType: ‘string’
}

routes :

const express = require("express");
const { createPost, likeAndUnlikePost } = require("../controllers/post");
const { isAuthenticated } = require("../middlewares/auth");

const router = express.Router();

router.route("/post/:id").get(isAuthenticated, likeAndUnlikePost);

module.exports = router;

models:

const mongoose = require("mongoose");

const postSchema = new mongoose.Schema({
  caption: String,
  image: {
    public_id: String,
    url: String,
  },
  owner: {
    type: mongoose.Schema.Types.ObjectId,
    ref: "User",
  },
  createdAt: {
    type: Date,
    default: Date.now,
  },
  likes: [
    {
      type: mongoose.Schema.Types.ObjectId,
      ref: "User",
    },
  ],
  comments: [
    {
      user: {
        type: mongoose.Schema.Types.ObjectId,
        ref: "User",
      },
      comment:{
        type: String,
        required: true,
      }
    },
  ],
});
module.exports = mongoose.model("Post", postSchema);

likeAndUnlikePost:

  try {
    const post = await Post.findById(req.params.id);

    if (!post) {
      return res.status(404).json({
        success: false,
        message: "Post not found",
      });
    }

    if (post.likes.includes(req.user._id)) {
      const index = post.likes.indexOf(req.user._id);

      post.likes.splice(index, 1);

      await post.save();

      return res.status(200).json({
        success: true,
        message: "Post Unliked",
      });
    } else {
      post.likes.push(req.user._id);

      await post.save();

      return res.status(200).json({
        success: true,
        message: "Post Liked",
      });
    }
  } catch (error) {
    res.status(500).json({
      success: false,
      message: error.message,
    });
    console.error(error)  }
};

4

Answers


  1. First verify if the _id exists. Then try converting the _id which is string, to ObjectId like

    mongoose.Types.ObjectId(req.params.id);
    
    Login or Signup to reply.
  2. Somewhere in your code you have assigned string value to _id (which is of type ObjectId)

    Login or Signup to reply.
  3. Alright my friend, I see the problem!

    Unlike the other answers, I actually ran your code.
    Seems like it’s working just fine as it is.
    You don’t need to change a thing in it!!!
    One issue though,
    look at the error you got:

    Cast to ObjectId failed for value "6283n"

    What is this value of "6283n"? That’s the problem!
    It seems like you have a user with an id of "6283n".
    Which means, it contains numbers AND a white-space, so the white-space makes it as string.
    So, while I said that there is NO problem with your code, there might be a problem with your User Model, which you haven’t shown us in this thread.

    The Answer – How to fix it

    Because I haven’t seen your User Model, I’ll make 2 guesses:

    1. You wanted/intended your User _id field to be of type ObjectId. If so, find out why you have a user with a weird _id value of "6283n", cause basically it’s two mistakes: A) Your _id is made up of numbers, i.e. Number type, while wanting ObjectId type. B) You got a 100% accidental space that slipped inside there. Find out how it got there.
    2. You wanted/intended your User _id field to be of type Number. If so, then this again splits into two problems: A) Your user _id still contains a white-space, which is what I assume 100% accidental. Find out its source. B) Your user _id is made up of numbers, which is what you want, but look at the array field inside your Post model, which contains a ref to your user. You state there that the User’s _id field is of type ObjectId, and not a Number, hence the mismatch.
    Login or Signup to reply.
  4. when i encounterd this error it was because i was using the get method instead of the post method

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search