Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

JavaScript User Authentication With Express and Mongo Sessions and Cookies Authenticating the Username and Password

Corey Hayden
Corey Hayden
11,717 Points

what exactly does the mongoose 'exec' method do?

it is called in the authenticate function...

UserSchema.statics.authenticate = function(email, password, callback) { User.findOne({ email: email }).exec(function (error, user){...}

the mongoose docs don't help me much...

http://mongoosejs.com/docs/api.html#query_Query-exec

1 Answer

Seth Kroger
Seth Kroger
56,407 Points

In Mongoose queries are composed but not necessarily run immediately. They return a query object that you can add (or chain) other queries to. The queries are all run as a unit when needed so there isn't any storing of unneeded intermediate results. This is what the exec() function does. You'll sometime hear it referred to as "lazy loading" or "lazy evaluation"

Tom Geraghty
Tom Geraghty
24,162 Points

This is the right answer. I just wanted to add on about your comment on the docs. That one is pretty short, but it indicates that the function returns a Promise. It's worth following the link in the exec docs to the Promises docs which has more information: http://mongoosejs.com/docs/api.html#promise_Promise There are some Treehouse videos on Promises as well.

This allows the function to be async and run when the data is made available (after the db findOne returns in this instance, or "lazy" loading resources that your app will use eventually as Seth mentioned).

I agree that Dave should state in the video that exec makes the function call resolve as a Promise, though.