Mongoose post-删除事件不会触发
Mongoose post-remove event doesn't fire
我的模型中有这段代码:
ContentSchema.post( 'remove', function( item ) {
index.deleteObject( item._id )
})
这是我的控制器中的内容:
Content.find( { user: user, _id: contentId } )
.remove( function ( err, count ) {
if ( err || count == 0 ) reject( new Error( "There was an error deleting that content from the stream." ) )
resolve( "Item removed from stream" )
})
我希望当控制器中的功能运行时,模型中的功能应该发生。我可以在调试器中看到它根本没有触发。
我正在使用 "mongoose": "3.8.23"
和 "mongoose-q": "0.0.16"
。
remove
事件(和其他中间件挂钩)不会在模型级方法上触发。如果使用实例方法,eg:
Content.findOne({...}, function(err, content){
//... whatever you need to do prior to removal ...
content.remove(function(err){
//content is removed, and the 'remove' pre/post events are emitted
});
});
...您将能够删除内容实例并触发 pre/post 删除事件处理程序。
这样做的原因是,为了让模型级方法按您预期的方式工作,必须获取实例并将其加载到内存中,并通过 Mongoose 执行的所有操作加载时到模型。顺便说一句,这个问题不是唯一需要解决的问题,任何模型级方法都会出现同样的问题(例如,Content.update
)。
这是 Mongoose 的一个已知怪癖(需要一个更好的词)。有关详细信息,请查看 Mongoose #1241.
我的模型中有这段代码:
ContentSchema.post( 'remove', function( item ) {
index.deleteObject( item._id )
})
这是我的控制器中的内容:
Content.find( { user: user, _id: contentId } )
.remove( function ( err, count ) {
if ( err || count == 0 ) reject( new Error( "There was an error deleting that content from the stream." ) )
resolve( "Item removed from stream" )
})
我希望当控制器中的功能运行时,模型中的功能应该发生。我可以在调试器中看到它根本没有触发。
我正在使用 "mongoose": "3.8.23"
和 "mongoose-q": "0.0.16"
。
remove
事件(和其他中间件挂钩)不会在模型级方法上触发。如果使用实例方法,eg:
Content.findOne({...}, function(err, content){
//... whatever you need to do prior to removal ...
content.remove(function(err){
//content is removed, and the 'remove' pre/post events are emitted
});
});
...您将能够删除内容实例并触发 pre/post 删除事件处理程序。
这样做的原因是,为了让模型级方法按您预期的方式工作,必须获取实例并将其加载到内存中,并通过 Mongoose 执行的所有操作加载时到模型。顺便说一句,这个问题不是唯一需要解决的问题,任何模型级方法都会出现同样的问题(例如,Content.update
)。
这是 Mongoose 的一个已知怪癖(需要一个更好的词)。有关详细信息,请查看 Mongoose #1241.