Reputation: 9477
Im following a course on Udemy for Node js. There mongoose pre middleware is used with remove like this.
ReviewSchema.pre('remove', function() {
// code goes here
});
But my implementation is different and I want to use findByIdAndDelete. This is my code.
ReviewSchema.pre('findByIdAndDelete', function() {
// code goes here
});
But this one doesn't trigger. I tried to console.log inside this, but it doesn't trigger. What am I doing wrong here?
Upvotes: 5
Views: 3301
Reputation: 2679
I believe that middleware doesn't exists. Take a look at the documentation.
But, if you go to findByIdAndDelete
's documentation then you will see that it triggers the following middleware:
findOneAndDelete
So, instead of ReviewSchema.pre('findByIdAndDelete', ...)
try ReviewSchema.pre('findOneAndDelete', ...)
.
Upvotes: 5
Reputation: 17858
There seems no middleware for findByIdAndDelete
.
But since findByIdAndDelete
triggers the findOneAndDelete
, you can take advantage of this.
So your ReviewSchema must be updated like this:
ReviewSchema.pre("findOneAndDelete", function() {
console.log("called!!!");
});
Also it is a good idea to include next() so that it does not stop the rest of the code in your middleware function from executing.
ReviewSchema.pre("findOneAndDelete", function(next) {
console.log("called!!!");
next();
});
Upvotes: 4