猫鼬JobSchema.pre('update',function(n){n()})引发:TypeError:无法读取未定义的属性'numAsyncPres' [英] Mongoose JobSchema.pre('update', function(n){n()}) throws: TypeError: Cannot read property 'numAsyncPres' of undefined

查看:118
本文介绍了猫鼬JobSchema.pre('update',function(n){n()})引发:TypeError:无法读取未定义的属性'numAsyncPres'的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的猫鼬有这个架构,当我将pre与update一起使用时,会出现此错误.

I have this Schema in mongoose and when I use the pre with update, I get this error.

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

注意:

  • pre(保存"工作
  • post('update'不会引发错误,也不起作用

推荐答案

Mongoose 4.0通过查询中间件支持预更新挂钩. http://mongoosejs.com/docs/middleware.html

Mongoose 4.0 supports pre update hooks via Query middleware. 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');
});

注意事项:

"查询中间件与文档中间件的区别在于: 重要方式:在文档中间件中,这是指文档 正在更新.在查询中间件中,猫鼬不一定具有 对要更新的文档的引用,因此是指查询 对象,而不是要更新的文档."

"Query middleware differs from document middleware in a subtle but important way: in document middleware, this refers to the document being updated. In query middleware, mongoose doesn't necessarily have a reference to the document being updated, so this refers to the query object rather than the document being updated."

这篇关于猫鼬JobSchema.pre('update',function(n){n()})引发:TypeError:无法读取未定义的属性'numAsyncPres'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆