Mongoose JobSchema.pre('update',function(n){n()})抛出:TypeError:无法读取未定义的属性'numAsyncPres'

Tot*_*.js 4 pre mongoose

我在mongoose中有这个Schema,当我使用pre更新时,我收到此错误.

JobSchema.pre('update', function(n){n()})
Run Code Online (Sandbox Code Playgroud)

完全错误

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
Run Code Online (Sandbox Code Playgroud)

笔记:

  • 预('保存'工作
  • post('update'不会抛出错误而不起作用

Jus*_*tin 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');
});
Run Code Online (Sandbox Code Playgroud)

注意事项:

" 查询中间件与文档中间件的区别在于一种微妙但重要的方式:在文档中间件中,这是指正在更新的文档.在查询中间件中,mongoose不一定对正在更新的文档有引用,所以是指查询对象而不是正在更新的文档."