Mongoose ODM, change variables before saving

I want to create a model layer with mongoose for my user documents, which does:

  1. validation (unique, length)
  2. canonicalisation (username and email are converted to lowercase to check uniqueness)
  3. salt generation
  4. password hashing
  5. (logging)

All of these actions require to be executed before persistment. Fortunatly mongoose supports validation, plugins and middleware.

The bad thing is just that I don't find any usable documentation about this topic. The official docs on mongoosejs.com are to short...

So has somebody an example about pre actions with mongoose (or a complete plugin which does all, if exists)?

Regards

In your Schema.pre('save', callback) function, this is the document being saved, and modifications made to it before calling next() alter what's saved.

Another option is to use Getters. Here's an example from the website:

function toLower (v) {
  return v.toLowerCase();
}

var UserSchema = new Schema({
  email: { type: String, set: toLower } 
});

http://mongoosejs.com/docs/getters-setters.html

var db = require('mongoose');
var schema = new db.Schema({
  foo:     { type: String }
});

schema.pre('save', function(next) {
  this.foo = 'bar';

  next();
});

db.model('Thing', schema);