Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongoose JobSchema.pre('update', function(n){n()}) throws: TypeError: Cannot read property 'numAsyncPres' of undefined

Tags:

mongoose

pre

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

JobSchema.pre('update', function(n){n()})

Full error

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

Notes:

  • pre('save' WORKS
  • post('update' Doesn't throw error and doesn't works
like image 775
Totty.js Avatar asked Dec 02 '22 21:12

Totty.js


2 Answers

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');
});

A note of caution:

"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."

like image 164
Justin Avatar answered Jan 01 '23 01:01

Justin


According to the Mongoose documentation, the pre and post middleware functions support:

  • init
  • validate
  • save
  • remove

No support for update.

like image 25
Greg Avatar answered Jan 01 '23 02:01

Greg