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 Improving the App with Custom Middleware Using Session Variables to Customize Content

Aleks Dahlberg
Aleks Dahlberg
19,103 Points

Help explaining the use of req.sessions.userId

I dont understand the use of req.session.userId throughout the app. Is it something that can only be attached to a users _id or can it be use as such:

req.session.userInfo = user; //user contains _id, name and password

or is req.session.userId something that can only be used with an _id as such:

req.session.userId = user._id; //user._id has only the user ID

1 Answer

Jonathan Foster
STAFF
Jonathan Foster
Treehouse Guest Teacher

It is better to only store only the user's ID in the session object rather than an entire user object. With only access to the ID of a user you must fetch the user object from the database with that ID and you are guaranteed to have the most up to date record of that user's information. The session is created when a user logs in and is not changed until it is destroyed when a user logs out. In a more complex application than the project in this course, perhaps a user can edit their own information. In that case you would have to update the session object with the user's new information if you wanted that data to remain accurate. Only storing the ID, which will never change, means there is a single source of truth for that user's information in the database. I hope that clears things up!