Mongoose error - no "toObject" method after update

I have a Mongoose model in which I call a method toObject

in a hook:

Product.post('init', function() {
   // if (typeof this.toObject === 'function') - works but why do I need it?
    this._original = this.toObject();
});

      

This has worked fine in the past, after updating Mongoose this error comes up:

TypeError: Object #<EventEmitter> has no method 'toObject'
at EventEmitter.Product.pre.self (/opt/run/snapshot/package/models/product.js:426:25)
at EventEmitter.emit (events.js:95:17)
at model.Document.(anonymous function) [as emit] (/opt/run/snapshot/package/node_modules/mongoose/lib/document.js:88:42)
at model.Document.init (/opt/run/snapshot/package/node_modules/mongoose/lib/document.js:271:8)
at completeMany (/opt/run/snapshot/package/node_modules/mongoose/lib/query.js:1075:12)
at Object.cb (/opt/run/snapshot/package/node_modules/mongoose/lib/query.js:1030:11)
at Object._onImmediate (/opt/run/snapshot/package/node_modules/mongoose/node_modules/mquery/lib/utils.js:137:16)
at processImmediate [as _immediateCallback] (timers.js:345:15)

      

I should note that this happens when the application starts. I can check to prevent the error, but the problem is that I need a toObject function and would like to understand how this error can be thrown.

I cannot find documents on any changes. Any ideas?

Edit . I realized that my problem was caused by the loose spec package.json

for Mongoose, which caused my host (nodejitsu) to use what I think is the version 4.x

instead of my local 3.8.x

branch. If I lock the version, the problem does not occur.

+3


source to share


1 answer


Somewhere between the late 3.8.x and 4.0, the post link init

was changed but not documented. Before the change, a this

reference to the current document, but is now this

the emitter of the event that caused the hook call. A new way to access the current document is to add a parameter to the hook function, just like pre save

and remove

hooks.

schema.post('init', function(doc) {
    doc._original = doc.toObject();
});

      



Unfortunately, since these changes are made, any non-schematic properties that are added to the doc will not get lost between the post init

and the pre- save

hooks, so there is no way to fix it right now.

I opened a question ( # 2952 ) on Github last Friday. There are currently 387 open questions so I'm not sure how quickly this will be fixed. I'll post an update if I hear anything.

+2


source







All Articles