给出简单的插件:
//plugin.js
module.exports = function (schema, options) {
schema.pre('save', function (done) {
console.log(this);
done();
});
schema.pre('validate', function (done) {
console.log(this);
done();
});
}
简单使用它:
//test.js
var mongoose = require('mongoose'),
plugin = require('./plugin');
describe('Example', function () {
beforeEach(connectToDb); // its a just example. code is pretty simple and should not be mentioned here
afterEach(disconnectDb);
it('should save', function (done) {
var scheme = new mongoose.Schema({
'prop' : String
});
scheme.plugin(plugin);
var model = mongoose.model('model', scheme);
var modelInstance = new model({ 'prop' : 'value' });
modelInstance.save(function (err) {
assert(!err);
done();
});
这里发生了什么?运行此代码后,我得到了:
undefined
undefined
有什么想法吗?为什么设置undefined? mongoose的版本是4.2.4
。