Search code examples
javascriptmongodbmongoose

post() callback function for deleteOne doesn't give the document object || Mongoose


ClubSchema.post('deleteOne', {document : true, query : true}, function (doc) {
    console.log('Running');
    console.log(doc);
    let club_id = doc._id;
    console.log(club_id);
});

Output (Whenever the deleteOne() function is called) :

Running
{acknowledged: true, deletedCount: 1}
undefined

I tried all variations and tweaking with the function - with and without the options parameters, checking out the second parameter that's passed into the callback function, etc. - but to no avail. I even tried the this keyword, but again it's undefined as well.

The following was the callback function definition in the package files :

type PostMiddlewareFunction<ThisType = any, ResType = any> = (this: ThisType, res: ResType, next: CallbackWithoutResultAndOptionalError) => void | Promise<void>;

And the example in the documentation gives the following example :

schema.post('deleteOne', function(doc) {
  console.log('%s has been deleted', doc._id);
});

I tried replicating this same example, but the doc parameter passed into the function seems to be different from the one here.

Anything that I'm missing here 🤷?

I have the same above post posted on github issues


Solution

  • The deleteOne,deleteMany returns the the database operations result, use removeOne or findOneAndDelete method instead if you want to return deleted document