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

Jason Pallone
Jason Pallone
11,340 Points

Where does user come from?

in the video, we use user, i know User is our schema, but this is the lowercase u user, where does it get defined and how?

Thanks!

2 Answers

Kevin D
Kevin D
8,646 Points
User.findById(req.session.userId)
  .exec(function (error, user) {
    if (error) {
      return next(error);
    } else {
      return res.render('profile', { title: 'Profile', name: user.name, favorite: user.favoriteBook });
    }
  });
  • The user part gets defined in function signature of the callback function:
    • .exec(function (error, user) {})
  • When the computer runs:
    • User.findById(req.session.userId)
  • If it finds the userId, it passes on the User data to the .exec callback function
  • You could call it whatever you wanted e.g. human for instance
    • .exec(function (error, human) {})
    • Then you could access the properties like this: human.name, human.favoriteBook

Further reading:

Jason Pallone
Jason Pallone
11,340 Points

So when using model.findOne() or .findbyId it will automatically pass it's value to the next .exec function, as the 2nd argument of that function?

Kevin D
Kevin D
8,646 Points

Yes, from looking at the docs/reference it looks like it will return the value (if found/successful) into the second parameter

Jason Pallone
Jason Pallone
11,340 Points

Ok that makes sense, thanks for the help!