node.jsexpressmongooseodm

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 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


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.