Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8786375
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 13, 20262026-06-13T21:36:29+00:00 2026-06-13T21:36:29+00:00

I want to refactor my user schema. The main reason for this decision is

  • 0

I want to refactor my user schema. The main reason for this decision is that I do not want to worry about password and salt generation. So I would like to move the encoding logic from the pre save handler to a setter. Unfortunately I do not have access from a setter to other properties of the object (like salt).

So defaulting a salt does not work and encoding a password with a salt also not.

My current implementation is:

var userSchema = new mongoose.Schema({

    username: { 
        type: String, 
        index: { unique: true, sparse: true }, 
        required: true, lowercase: true, trim: true
    },

    email: {
        type: String,
        index: { unique: true, sparse: true }, 
        required: true, lowercase: true, trim: true
    },

    salt: {
        type: String,
        select: false
    },

    password: {
        type: String,
        select: false
    },

    plainPassword: {
        type: String,
        select: false
    }

});

// FIXME: password encoding only on change, not always
userSchema.pre('save', function(next) {
    // check if a plainPassword was set
    if (this.plainPassword !== '') {
        // generate salt
        crypto.randomBytes(64, function(err, buf) {
            if (err) return next(err);
            this.salt = buf.toString('base64');
            // encode password
            crypto.pbkdf2(this.plainPassword, this.salt, 25000, 512, function(err, encodedPassword) {
                if (err) return next(err);
                this.password = new Buffer(encodedPassword, 'binary').toString('base64');
                this.plainPassword = '';
            }.bind(this));
        }.bind(this));
    }

    next();
});

// statics
userSchema.methods.hasEqualPassword = function(plainPassword, cb) {
    crypto.pbkdf2(plainPassword, this.salt, 25000, 512, function(err, encodedPassword) {
        if (err) return next(err);
        encodedPassword = new Buffer(encodedPassword, 'binary').toString('base64');
        cb((this.password === encodedPassword));
    }.bind(this));
}

module.exports = mongoose.model('User', userSchema, 'Users');

Has somebody managed to move encryption to mongoose setters?

Regards, bodo

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-13T21:36:31+00:00Added an answer on June 13, 2026 at 9:36 pm

    You DO have access to other properties from within the setter with the use of the this keyword. For example:

    userSchema.path('pass').set(function(v) {
    
      console.log(this); // Returns model instance
    
      return v;
    
    });
    

    However, setters are unfit for your use case. As you probably know, HMAC-SHA1 is super expensive and therefore will block unless performed asynchronously. Mongoose setters require the function to return a value and there is no way to route the result of crypto.pbkdf2()’s callback to the return value of the setter function. This is a limitation of asynchronous javascript and not Mongoose itself: you can’t wrap an async call within a sync function, as this destroys the nature of the async chain.

    Setters are most widely used for simple string manipulations and data sanitization.

    Here is a demo for encryption using only instance methods:

    // Model method
    userSchema.methods.hashPassword = function(pass, callback) {
      // Generate salt (this should probably be async too)
      var salt = this.salt = crypto.createHash('md5').update(Math.random().toString()).digest('hex');
      // Salt and Hash password
      crypto.pbkdf2(pass, salt, 25000, 512, callback);
    });
    
    // Implementation
    var user = new User({
      email: req.body.email
    });
    user.hashPassword(req.body.pass, function(err, hash){
      user.pass = hash; 
      user.save();
    });
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I want to refactor some C# modules that read data from SQL Server 2008
I want to refactor many similar controls that only differ in the value of
I want to refactor this piece of code, it takes input from a form,
I have a spring mvc app that I want to refactor out, speficially removing
I have a bunch of scripts which I want to refactor into modules. This
I am unsure how to go about this, I want to add unique identifiers
Hi Guys could you please help me refactor this so that it is sensibly
I am trying to refactor a solution that includes 2 MVC projects: a User-Experience
i want refactor variables names. variable_foo to variableFoo Is it possible to do this
I want to refactor multiple classes that I think should derive from one base

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.