为什么这段代码会因为“你应该找不到我”错误信息失败而不是只打印“保存存根被叫”并退出?
var mongoose = require('mongoose'),
Schema = mongoose.Schema,
modelSchema,
ModelClass,
modelInstance;
modelSchema = new Schema({name: {type: String}});
modelSchema.pre('save', function (next) {
throw new Error('you should have stubbed me');
});
ModelClass = mongoose.model('Model', modelSchema);
ModelClass.prototype.save = function () { console.log('Save stub called'); }
modelInstance = new ModelClass();
modelInstance.save();
我已经看到这种存储模型的保存功能的方法非常普遍推荐,所以我很惊讶它并没有阻止预保存挂钩也被执行。
答案 0 :(得分:0)
添加行Schema.prototype.pre = function () {};
解决了这个问题。
var mongoose = require('mongoose'),
Schema = mongoose.Schema,
modelSchema,
ModelClass,
modelInstance;
Schema.prototype.pre = function () {};
modelSchema = new Schema({name: {type: String}});
modelSchema.pre('save', function (next) {
throw new Error('you should have stubbed me');
});
ModelClass = mongoose.model('Model', modelSchema);
ModelClass.prototype.save = function () { console.log('Save stub called'); }
modelInstance = new ModelClass();
modelInstance.save();