Mongoose post-remove event doesn't fire

℡╲_俬逩灬. 提交于 2019-12-07 13:38:25

问题


I have this code in my model:

ContentSchema.post( 'remove', function( item ) {
    index.deleteObject( item._id )
})

Here's what's in my controller:

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

I expect that when the function in the controller runs, the function in the model should happen. I can see in the debugger it does not fire at all.

I'm using "mongoose": "3.8.23" and "mongoose-q": "0.0.16".


回答1:


The remove events (and other middleware hooks) are not fired on model-level methods. If you use an instance method, 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
    });
});

... you will be able to remove the content instance and have the pre/post remove event handlers fire.

The reason for this is because in order for the model-level methods to work as you would expect, the instance would have to be fetched and loaded into memory, as well as go through all of the sugar that Mongoose does to models when loading. By the by, this problem is not unique to remove, any model-level method would exhibit the same issue (eg, Content.update).

This is a known quirk (for want of a better word) of Mongoose. For more information, check out Mongoose #1241.



来源:https://stackoverflow.com/questions/29016354/mongoose-post-remove-event-doesnt-fire

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!