Chat GPT Helped debug my code and taught me!

I’ve been working on the Exercise Tracker for 2 days now and have posted 4 questions after finding similar, but not identical, but have received zero responses to my queries.

Two I solved on my own but still had errors on testing despite it working for me fine. Now I’m sure a lot of the experienced coders would spot some errors right away, but the “Cast Error” was driving me crazy.

Here is the conversation:
me:
can you help me with my node.js and express project?

Chat:
Of course! What do you need help with specifically in your Node.js and Express project?

me:
i need help understanding why this piece of code gives me a “cast error”


// save new exercise from form
app.route('/api/users/:_id/exercises')
  .post((req, res) => {                                    //receive form data
    console.log(req.body);
    console.log(req.params);
    console.log(req.query);
    let exerciseDate = new Date()

    let userID = req.params._id
    console.log(userID)

    User.findById({ _id: userID }, function(err, user) {
      console.log(user)
      if (err) return console.log(err)
      if (req.body.date != '') {
        let exerciseDate = req.body.date
      }

      var exercise = new Exercise({
        username: user.username,
        descpription: req.body.description,
        duration: req.body.duration,
        date: exerciseDate
      })

      exercise.save(function(err, data) {
        if (err) return console.err(err);
        done(null, exercise);
      })
      console.log(exercise)
      res.json(exercise)

    })


  }
  )

Chatbot:

The “cast error” is likely caused by the fact that the userID being passed as a parameter in the findById method is not a valid MongoDB ObjectId. The findById method is used to find a single document by its _id field, which must be a valid ObjectId.

It seems that you are trying to get user id from req.params._id, and use it to find the user in your database. But, if the user id is passed as a string in the request, you need to convert it to a ObjectId before passing it to the findById method. You can do this by using the mongoose.Types.ObjectId function, like this:

const mongoose = require('mongoose');
let userID = mongoose.Types.ObjectId(req.params._id);

Also, it seems that you are using a callback function to find the user, but you are not handling the error properly. You should check if the error is null, if not, return the error, like this:

User.findById({ _id: userID }, function(err, user) {
    if (err) return res.status(400).json({error : "user not found"});
    // your code
}

Also, in the code you shared, console.err(err); should be console.error(err);. Additionally, done(null, exercise); should not be there, as done is not defined in the scope.

Let me know if this helps or if you have any other questions.

Holy smokes…it worked and I am floored!!

1 Like

Are you certain this works they way you/chat gpt think it does?

To preface, I haven’t used Mongoose but the documentation contradicts some of what you said…

https://mongoosejs.com/docs/api.html#model_Model-findById

based on this you should be able to pass the userID string to the findById. I’m not sure why you’re passing an object with an _id key.

Seems like you are confusing this with findOne

also IMO you’d want to return a 404 if the user wasn’t found.

Hey thanks for your feedback. I did end up changing the code all around anyway, but I made this change suggested and it worked, but didn’t work for some later challenges. I forget all the details now but you’re right…wonder if I should just remove this thread so as not to confuse anyone?

We need to see all the code. I’m guessing the cast error might have to do with how you defined the id in the schema (which you usually do not even need to do).


I haven’t personally tried ChatGPT yet but I do think you have to be careful with how you use it. If you can not verify the answer because you do not have the knowledge to do so it can pretty much tell you anything. In the end, the onus is on you to verify it.

I do think it might be interesting to see it set up for pair programming, and see how it handles the driving and navigation.

1 Like

I agree. The answers it gave me seemed to be something right out of the mongo / express / mongoose / node docs but collated to give me a cohesive answer without me having to look up 4 different sets of docs.

I eventually passed the challenge but if you’re willing I could share my code to see what bad practices I am guilty of so I can improve

so chatGPT is not better than human programmers afterall?

1 Like