0
votes

I am using a sample MongoDB Database for a project, while using the findById mongoose method, I get the error: 'CastError: Cast to ObjectId failed for value "..." at path "_id" for model "Company"'. I am using handlebars as the view engine.

error

Middleware file:

getCompanyData: async (req, res, next) => {
    // Queries
    const information =
      "name ipo founded_day founded_month founded_year description overview relationships";
    // try {
      const getCompanyData = await Companies.findById(req.params.id, information).exec();
      console.log(getCompanyData);
      // Coverting Mongoose Document to Object
      const companyData = getCompanyData.toObject()
      // console.log(companyData); 

Here is the routes file

// Company Route
router.get('/list/:id', getCompanyData, (req, res) => {
  // console.log(req.companyData.name);
  res.render('company', {
    comapany: req.companyData
  })
})

1
why are you passin the variable information in findById(),I dont think you can do such way. what are you trying to achieve btw?Karl L
He is trying to fetch some selective fields from result using the 2nd perameter as a string.Ankit
Please console.log(req.params.id) and try to typecast it to object Id. id = mongoose.Types.ObjectId(req.params.id)Ankit

1 Answers

1
votes

If what you are encountering is the same thing as I encountered previously...this is caused by the sequence of your route code. Make sure when you use params on your routes you put

// Company Route
router.get('/list/:id', getCompanyData, (req, res) => {
  // console.log(req.companyData.name);
  res.render('company', {
    company: req.companyData
  })
})

ALL THE WAY TO THE BOTTOM of your code...because lets say you had another route /list/profile...it will give you that error because profile is not an objectId.