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
First verify if the _id exists. Then try converting the _id which is string, to ObjectId like
Somewhere in your code you have assigned string value to
_id
(which is of typeObjectId
)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:
when i encounterd this error it was because i was using the get method instead of the post method