[SOLVED] CastError: Cast to ObjectId failed for value "{ articleId: 5f4ebe073c6a0d23745063d0 }" at path "_id" for mode l "Article"

When I click My Article button from the homepage I get the following error :
CastError: Cast to ObjectId failed for value “{ articleId: 5f4ebe073c6a0d23745063d0 }” at path “_id” for mode
l “Article”

Repo : https://github.com/Mxk01/Blog-Auth-issue

I am trying to make article posts unique to logged in user .Any help would be greatly appreciated :slight_smile:

If you post the relevant code right in the forum here I’d take a look at it

I think this is the route where I’m having issues (in articleController.js) :

seeMyArticle:async(req,res)=>{
  console.log(req.user._id);
  const articles =  await Article.findById({articleId:req.user._id});
    res.render('myArticles',{articles});
  console.log('Hello');
}

This is how I set up my article model :

let mongoose = require('mongoose');
let Schema = mongoose.Schema;
let articleSchema = new Schema(
{
  articleId:
  {

    
      type:Schema.Types.ObjectId, 
      ref:'User'
  },
title:
{
  type:String
},
description:
{
  type:String
},
markdown:
{
  type:String
},
createdAt:
{
  type:Date,
  default:Date.now
}

},{timestamps:true});


module.exports = mongoose.model('Article',articleSchema);

So how did you solve this? i am having the exact same issue. it has something to do with FindById
Edit: So apparently there was a problem i overlooked ( I bet many will run into this problem)
Make sure to do something.findById(userId) instead of something.findById({userId}) do not pass the expected id inside of the brackets or this error will be thrown.

Good luck

2 Likes