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!!