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 Storing Passwords Securely

Vitaly Khe
Vitaly Khe
7,160 Points

Need help on Mongoose methods and using JS keyword "this" inside

I feel frustrated : How can we bind "this" with real instance data inside of a schema(shape of document) definition code?

UserSchema.pre('save', function(next) {
  const user = this;
  try {
    bcrypt.hash(user.password, 10, function(err, hash) {
      user.password = hash;
      next();
    }
  }
  catch (err) {
    return next(err);
  }
});

In mongo documentation described that model but not Schemais a database object. And instance of a model is a document.

So, it is out of my understanding why not we use "this" and encryption inside of a model definition(constructor?) but Schema.pre...

Completely lost. Pls help

1 Answer

Vitaly Khe
Vitaly Khe
7,160 Points

Well, I'm answering to myself here. Maybe the answer will be helpful for other. If some of moderators look this: pls let us have added the link below to the Teacher notes.

https://mongoosejs.com/docs/middleware.html#pre

Mongoose has 4 types of middleware: document middleware, model middleware, aggregate middleware, and query middleware. Document middleware is supported for the following document functions. In document middleware functions, this refers to the document. **

  • validate
  • save
  • remove
  • init (note: init hooks are synchronous) **