我在我的模型中有这个代码: ContentSchema.post( 'remove', function( item ) { index.deleteObject( item._id )}) 这是我的控制器中的内容: Content.find( { user: user, _id: contentId } ).remove( function ( err, count ) {
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”.
删除事件(和其他中间件挂钩)不会在模型级方法上触发.如果您使用实例方法,例如: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对模型所做的所有糖.通过by,这个问题不是唯一的删除,任何模型级方法都会表现出相同的问题(例如,Content.update).
这是Mongoose的一个已知的怪癖(想要更好的词).有关更多信息,请查看Mongoose #1241.
