Supertest and Mongoose Middleware (post remove) Supertest and Mongoose Middleware (post remove) mongoose mongoose

Supertest and Mongoose Middleware (post remove)


Here's what I suggest. Let's perform the #remove on the doc found by #findOne. If I remember correctly, remove post hooks only works on Doc#remove and not on Model#remove.

schema.post('remove', function (doc) {    console.log('doctors - post - remove'); // <-- now runs});app.delete('/doctors/remove', authController.isAuthenticated, function (req, res, next) {    var email = req.user['email'];    Doctors.findOne({email: email}, function(err, doc) {      if (err) {        return next(err);      }      doc.remove().then(function(removed) {        return res.status(200).send(removed);      }, function(err) {        next(err);      });    });});


Mongoose post hooks run AFTER the operation is completed, concurrently with operation callbacks. See the comments below:

Doctors.findOne({email:email}).remove(function (err, removed) {    // All this code and the post hook are executed at the same time    if (err) return next(err);    // Here you send the response so supertest#end() will be triggered    // It's not guaranteed that post remove was executed completely at this point    return res.status(200).send(removed);});

Post hooks were made to run processes independent of the server response. When you run tests, the server shuts down right after the tests are completed, and maybe it had no time enough to finish the post hooks. In the other hand, when you call the API from a client, normally you keep the server running, so the post jobs can be completed.

Now, there comes a problem: how can we test post hooks consistently? I got up this question because I was looking for a solution to that. If you already have an answer, please post here.