I want to create a model layer with mongoose for my user documents, which does:
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 }
});
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);