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 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,413 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,174 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.