var schema = new Schema(..);
schema.pre('save', function(next) {
// do stuff
next();
});
Parallel (并行)
并行中间件提供了更多的细粒度的流量控制。
var schema = new Schema(..);
// `true` means this is a parallel middleware. You **must** specify `true`
// as the second parameter if you want to use parallel middleware.
schema.pre('save', true, function(next, done) {
// calling next kicks off the next middleware in parallel
next();
setTimeout(done, 100);
});
钩子方法,在这种情况下,保存,将不会被执行,直到完成每个中间件。
使用案例
中间件用于雾化模型逻辑和避免嵌套异步代码块。这里有一些其他的想法:
complex validation removing dependent documents (removing a user removes all his blogposts) asynchronous defaults asynchronous tasks that a certain action triggers triggering custom events notifications
杂的验证
删除相关文件
(删除一个用户删除了他所有的博客文章)
异步默认
异步任务,某些动作触发器
引发自定义事件
通知
错误处理
如果任何中间件调用next或done一个类型错误的参数,则流被中断,并且将错误传递给回调。
schema.pre('save', function(next) {
// You **must** do `new Error()`. `next('something went wrong')` will
// **not** work
var err = new Error('something went wrong');
next(err);
});
// later...
myDoc.save(function(err) {
console.log(err.message) // something went wrong
});
后置中间件(Post middleware)
后置中间件被执行后,钩子的方法和所有的前置中间件已经完成。后置的中间件不直接接收的流量控制, 如: 没有 next 或 done回调函数传递给它的。后置钩子是是一种来为这些方法注册传统事件侦听器方式。
schema.post('init', function(doc) {
console.log('%s has been initialized from the db', doc._id);
});
schema.post('validate', function(doc) {
console.log('%s has been validated (but not saved yet)', doc._id);
});
schema.post('save', function(doc) {
console.log('%s has been saved', doc._id);
});
schema.post('remove', function(doc) {
console.log('%s has been removed', doc._id);
});
// Takes 2 parameters: this is an asynchronous post hook
schema.post('save', function(doc, next) {
setTimeout(function() {
console.log('post1');
// Kick off the second post hook
next();
}, 10);
});
// Will not execute until the first middleware calls `next()`
schema.post('save', function(doc, next) {
console.log('post2');
next();
});