3

我的模型中有这段代码:

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"

4

1 回答 1

11

事件remove(和其他中间件挂钩)不会在模型级方法上触发。如果您使用实例方法,例如:

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

...您将能够删除内容实例并触发前/后删除事件处理程序。

这样做的原因是,为了让模型级别的方法按您的预期工作,必须获取实例并将其加载到内存中,并且在加载时通​​过 Mongoose 对模型所做的所有糖。顺便说一句,这个问题并不是唯一要消除的,任何模型级方法都会表现出相同的问题(例如,Content.update)。

这是 Mongoose 的一个已知怪癖(因为缺少更好的词)。有关更多信息,请查看Mongoose #1241

于 2015-03-14T22:57:56.727 回答