猫鼬错误-升级后没有'toObject'方法 [英] Mongoose error - no 'toObject' method after upgrade
问题描述
我有一个Mongoose模型,在其中用钩子调用toObject
方法:
I have a Mongoose model in which I call the toObject
method 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 pastbut after a Mongoose upgrade this error is thrown:
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)
我应该注意,启动应用程序时会发生这种情况.我可以进行检查以防止错误,但是问题是我需要toObject函数,并且想了解如何引发此错误.
I should note that this occurs when launching the app. I can do a check to prevent error but the issue is that I need the toObject function and would like to understand how this error can be thrown.
我没有找到有关任何更改的文档.有什么想法吗?
I am not finding docs on any changes. Any ideas?
编辑我意识到我的问题是由于Mongoose的package.json
规范宽松导致主机(nodejitsu)使用了我认为的4.x
版本而不是本地的
Edit I realized my issue was caused by a loose package.json
spec for Mongoose which caused my host (nodejitsu) to use what I think is a 4.x
version instead of my local 3.8.x
branch. If I lock down the version exactly the problem does not occur.
推荐答案
在最新版本3.8.x和4.0之间的某个地方,发布了init
钩子,但未进行记录.更改之前,this
引用了当前文档,但是现在this
是触发挂接调用的事件发射器.访问当前文档的新方法是在挂钩函数中添加一个参数,就像之前的save
和remove
挂钩一样.
Somewhere between the late version 3.8.x and 4.0 the post init
hook was changed, but not documented. Prior to the change this
referenced the current document, but now this
is the event emitter that triggered the hook call. The new way to access the current doc is by adding a parameter to the hook function, just like the pre save
and remove
hooks.
schema.post('init', function(doc) {
doc._original = doc.toObject();
});
不幸的是,由于此更改,添加到文档中的所有非架构属性似乎在后init
和前save
钩子之间丢失了,因此现在无法解决此问题.
Unfortunately, since this change, any non-schema properties that are added to the document appear to be lost between the post init
and pre save
hooks, so there's no way to fix this right now.
我上周五在Github上发布了一个问题(#2952 ).当前有387个未解决的问题,因此我不确定该解决的速度有多快.如果我听到任何声音,我会发布更新.
I opened an issue (#2952) on Github last Friday. There are currently 387 open issues, so I'm not sure how quickly this will get resolved. I'll post an update if I hear anything.
这篇关于猫鼬错误-升级后没有'toObject'方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!