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 User Registration Adding Data to the Database

Brendan Moran
Brendan Moran
14,052 Points

Why is the second argument, "user" passed in to the User.create() callback function?

In the code

User.create(userData, (error, user) => {
        if(error) {
          return next(error)
        } else {
          return res.redirect('/profile')

Why the user parameter? It is not used, and I wonder how it would be used.

Also, a general question about express (or maybe some piece of my javaScript/programming knowledge in general that is missing): why all the return statements? Why can't you just do next(error) and res.redirect('profile')? My thinking is that these are function calls that will exit the current function anyway, and they are called in if/else blocks, where there is no more code left to run even if the control flow were to come back to the current function. Someone please educate me on this or point me to the right docs! :D

2 Answers

Hey Brendan,

That user parameter contains the userData along with other information, like the user's unique __id. This parameter is actually used later on in the course for this very reason: we use it to retrieve the __id so we can assign it to the request object as a session ID.

As for your second question, given the code you've posted above, you'd be right: because the logic is if-else β€” and nothing else β€” a return statement is redundant. Most of the other cases in the app, however, are not like this. If you look at the rest of the codebase for this app, the return statements are employed effectively.

The user object most likely refers to the query result. When an insert is successful, Mongo always returns an object of the inserted document. The return statements will cancel any following middleware. Otherwise, they will be automagically invoked.