Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript User Authentication With Express and Mongo Sessions and Cookies Creating the Profile Route and Page

Receive 'Cast to ObjectId Failed' error after trying to login

After this video, I'm able to create a user just fine but when I try to login as the user, I receive this error:

Cast to ObjectId failed for value "5875bc88aaabde0fdd2804d8" at path "_id" for model "User"

The _id matches what is in the mongo database, so I am not sure what the issue is. I even ran a diff checker for my index.js route file and user.js model file to compare them against the ones found for the next video and it didn't find any diff.

Jonathan Kuhl
Jonathan Kuhl
26,133 Points

I had a similar issue. Turns out if you do request.session.id, you'll get this error. session.id is used internally and will overwrite whatever you assign to it, and it will therefore be invalid if you try to use it in Mongo's object() type (which is a 24 character hex value.) You have to make sure that you call the id something else like userId as Dave does.

If the userId matches the hex value in the Object in your mongo document's _id value, then you should be fine.