我在mongoose中有这个Schema,当我使用pre更新时,我收到了这个错误。
JobSchema.pre('update', function(n){n()})
完整错误
C:\web\production01_server\node_modules\production\node_modules\mongoose\lib\utils.js:413
throw err;
^
TypeError: Cannot read property 'numAsyncPres' of undefined
at Model._lazySetupHooks (C:\web\production01_server\node_modules\production\node_modules\mongoose\node_modules\hooks\hooks.js:149:49)
at Model.pre (C:\web\production01_server\node_modules\production\node_modules\mongoose\node_modules\hooks\hooks.js:113:10)
at Model.doQueue (C:\web\production01_server\node_modules\production\node_modules\mongoose\lib\document.js:1116:41)
at Model.Document (C:\web\production01_server\node_modules\production\node_modules\mongoose\lib\document.js:55:8)
at Model.Model (C:\web\production01_server\node_modules\production\node_modules\mongoose\lib\model.js:26:12)
at Model.model (C:\web\production01_server\node_modules\production\node_modules\mongoose\lib\model.js:910:11)
at new Model (C:\web\production01_server\node_modules\production\node_modules\mongoose\lib\connection.js:418:15)
at cb (C:\web\production01_server\node_modules\production\node_modules\mongoose\lib\query.js:804:16)
at C:\web\production01_server\node_modules\production\node_modules\mongoose\lib\utils.js:408:16
at C:\web\production01_server\node_modules\production\node_modules\mongoose\node_modules\mongodb\lib\mongodb\cursor.js:133:9
注意:
答案 0 :(得分:9)
Mongoose 4.0通过Query中间件支持预更新挂钩。 http://mongoosejs.com/docs/middleware.html
schema.pre('update', function() {
console.log(this instanceof mongoose.Query); // true
this.start = Date.now();
});
schema.post('update', function() {
console.log(this instanceof mongoose.Query); // true
console.log('update() took ' + (Date.now() - this.start) + ' millis');
});
注意事项:
“查询中间件与文档中间件的区别在于微妙但 重要的方法:在文档中间件中,这是指文档 正在更新。在查询中间件中,mongoose不一定有 对正在更新的文档的引用,因此此指的是查询 对象而不是文档正在更新。“
答案 1 :(得分:4)
答案 2 :(得分:3)
除了上面列出的Greg之外,Mongoose不支持模型API上的钩子,这是真的。但是,可以通过Monkey-patch完成更新挂钩。 Hooker NPM包是干净利落的好方法。
RESTeasy项目是节点REST API的Boilerplate,其代码演示了如何执行此操作:
var hooker = require('hooker');
var BaseSchema = new mongoose.Schema({
sampleString: {
type: String
}
});
var BaseModel = mongoose.model('Base', BaseSchema);
// Utilize hooks for update operations. We do it in this way because MongooseJS
// does not natively support update hooks at the Schema level. This is a way
// to support it.
hooker.hook (BaseModel, 'update', {
pre: function () {
// Insert any logic you want before updating to occur here
console.log('BaseModel pre update');
},
post: function () {
// Insert any logic you want after updating to occur here
console.log('BaseModel post update');
}
});
// Export the Mongoose model
module.exports = BaseModel;
答案 3 :(得分:1)
我发现了这个:https://github.com/LearnBoost/mongoose/issues/538 所以没有预先更新...