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 trialLucas Santos
19,315 PointsCan you please explain your use of the .exec method
I understand what the .exec method is and that it's a method on the RegularExpression Object but the way you use this function does not make sense or was not explained very well. From my understanding the method is suppose to match a string with the expression but instead your giving it an anonymous function??
You used it twice:
- in the User Schema:
UserSchema.statics.authenticate = function(email, password, callback) {
User.findOne({ email: email })
.exec(function (error, user) {
if (error) {
return callback(error);
} else if ( !user ) {
var err = new Error('User not found.');
err.status = 401;
return callback(err);
}
bcrypt.compare(password, user.password , function(error, result) {
if (result === true) {
return callback(null, user);
} else {
return callback();
}
})
});
}
and 2. on the route for /profile
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 });
}
});
thank you.
2 Answers
akak
29,445 PointsHi, You are correct there is an .exec method on a Regex object. But since it's not on reserved methods name list: http://www.w3schools.com/js/js_reserved.asp anyone can create:
var myObject = {
exec: function () {
return 'Hello world';
}
}
and you would do myObject.exec()
to get hello world;
You can read more about mongoose exec here: http://mongoosejs.com/docs/queries.html.
In short: exec just executes your query and runs callback function with the data from the query.
Marcus Thelin
1,188 PointsSo as I see it, the .exec function is used to easily handle error and the result from mongoose. If you're only interesting in getting the user into some variable, you can do it in an async-await function e.g
async function(){
let user = await User.findOne({INFO TO SEARCH}); //Stores the user in the user variable
}
But in this case the exec function is the best usage! :D Happy coding!
Lucas Santos
19,315 PointsLucas Santos
19,315 PointsAhh I see so that's where the confusions lies. Thanks for the head up akak!