Remove hook not triggered when removing documents
See original GitHub issueThe pre/post hooks for remove
are only triggered when using the document instance’s remove()
method, not when the model’s methods are used:
var mongoose = require("mongoose");
var db = mongoose.createConnection('mongodb://localhost/experiment');
db.once('open', function(){
testSchema = new mongoose.Schema({ title: String });
testSchema.post('remove', function(removed){
console.log('removed', removed.title);
});
var Test = db.model('Test', testSchema);
// > "removed A"
new Test({ title: 'A' }).save(function(err, created){
created.remove();
});
// Nothing :(
Test({ title: 'B' }).save(function(err, created){
Test.remove({ title: 'B' }).exec();
});
// Nothing :(
Test({ title: 'C' }).save(function(err, created){
Test.find({ title: 'C' }).remove();
});
});
Issue Analytics
- State:
- Created 11 years ago
- Comments:24 (6 by maintainers)
Top Results From Across the Web
"pre" and "post" remove Middleware not firing - Stack Overflow
Because no Mongoose documents are involved, no middleware (hooks) are executed. In the above example, the doc was first found, and then removed....
Read more >Middleware pre('remove', ...) not getting called - Google Groups
This method sends a remove command directly to MongoDB, no Mongoose documents are involved. Because no Mongoose documents are involved, no middleware (hooks) ......
Read more >Mongoose v6.8.1: Middleware
updateOne() trigger updateOne hooks, but this refers to a query, not a document. To register updateOne or deleteOne middleware as document middleware, ...
Read more >useHooks - Easy to understand React Hook recipes
We bring you easy to understand React Hook code recipes so you can learn how React hooks work and feel more comfortable writing...
Read more >Cloud Firestore triggers | Cloud Functions for Firebase
An update to a Cloud Firestore document, where data is unchanged (a no-op write), ... Get an object with the previous document value...
Read more >Top Related Medium Post
No results found
Top Related StackOverflow Question
No results found
Troubleshoot Live Code
Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start FreeTop Related Reddit Thread
No results found
Top Related Hackernoon Post
No results found
Top Related Tweet
No results found
Top Related Dev.to Post
No results found
Top Related Hashnode Post
No results found
Top GitHub Comments
This is how I got around the issue:
The remove hook is not fired on findOneAndRemove, however, it works when I call remove in the callback
Ok but Why ? iam sorry i didnt get why the hook is executed on Model.remove() and not on Query.remove(). Now why should i use the hooks if they arent called everytime ?
what’s the use ?