猫鼬移除后事件不会触发 [英] Mongoose post-remove event doesn't fire

查看:73
本文介绍了猫鼬移除后事件不会触发的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的模型中有以下代码:

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.

我正在使用"mongoose": "3.8.23""mongoose-q": "0.0.16".

推荐答案

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

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

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

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

这样做的原因是,为了使模型级方法能够按您期望的那样工作,必须将实例提取并加载到内存中,并遍历Mongoose对模型所做的所有工作加载时.顺便说一句,这个问题并不是唯一可以解决的问题,任何模型级方法都会出现相同的问题(例如,Content.update).

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).

这是猫鼬的一个已知古怪(由于缺少更好的词).有关更多信息,请查看猫鼬#1241 .

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

这篇关于猫鼬移除后事件不会触发的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆