Mongoose ODM, change variables before saving

express, mongoose, node.js, odm

Solution

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.

Problem

I want to create a model layer with Mongoose for my user documents, which does: - validation (unique, length) - canonicalisation (username and email are converted to lowercase to check uniqueness) - salt generation - password hashing - (logging) All of these actions are required to be executed before persisting to the db. Fortunately mongoose supports validation, plugins and middleware. The bad thing is that I cannot find any good material on the subject. The official docs on mongoosejs.com are too short... Does anyone have an example about pre actions with Mongoose (or a complete plugin which does all, if it exists)? Regards

Original source