我有一个猫鼬模型,我称之为toObject
钩子中的方法:
Product.post('init', function() {
// if (typeof this.toObject === 'function') - works but why do I need it?
this._original = this.toObject();
});
这在过去工作得很好,但在 Mongoose 升级后会抛出此错误:
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 函数,并且想了解如何引发此错误。
我没有找到有关任何更改的文档。有任何想法吗?
Edit我意识到我的问题是由松动引起的package.json
Mongoose 的规范导致我的主机(nodejitsu)使用我认为的4.x
版本而不是我的本地版本3.8.x
分支。如果我完全锁定版本,则不会出现问题。
介于最新版本 3.8.x 和 4.0 之间的帖子init
钩子已更改,但未记录。变更前this
引用了当前文档,但现在this
是触发钩子调用的事件发射器。访问当前文档的新方法是在钩子函数中添加一个参数,就像 pre 一样save
and remove
hooks.
schema.post('init', function(doc) {
doc._original = doc.toObject();
});
不幸的是,由于此更改,添加到文档中的任何非架构属性似乎在发布之间丢失init
和预save
钩子,所以现在没有办法解决这个问题。
我打开了一个问题(#2952 https://github.com/Automattic/mongoose/issues/2952)上周五在 Github 上。目前有 387 个未解决的问题,所以我不确定这个问题能多快得到解决。如果我听到任何消息,我会发布更新。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)