Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Hooks In Node.js

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 216
    Comment on it

    Hooks are used to add any functionality before or after our JavaScript methods like save, create etc. Using hooks we are able to write the code that can be run before or after save method.

    Suppose you have a User model, in that you have a password field, so we need to encrypt the password before saving it to the database. In that situation we can use hooks.

    For example i have a model/user.js file with the code below:

    var mongoose     = require('mongoose');
    var Schema       = mongoose.Schema;
    
    var UserSchema   = new Schema({
        username: { type: String, unique: true, require: true},
        email: { type: String, require: true},
        password: { type: String, require: true},
        role: {type: String    }
        
    });
    
    
    UserSchema.pre('save', function(next) {
      console.log("I am a hook inside User model")
      this.password = require('crypto').createHash('sha1').update(this.password).digest('base64');
      next();
    });
    
    var User = mongoose.model('User', UserSchema);
    
    module.exports = User;

    Now whenever you call save() method upon User model first it will execute the functionality of the pre hook, which means before saving the data in the collection , it will encrypt the password and then it will be saved.To confirm you can see the output in console.

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: