alexhzr
alexhzr

Reputation: 153

How to cascade delete using Mongoose remove middleware?

I'm trying to delete all dependencies of a schema when a DELETE request is sent to my API. Deleting goes ok, but the remove middleware, which is supposed to clean the dependencies, seems like is not even getting called.

This is my Customer schema:

var mongoose = require("mongoose"),
Schema = mongoose.Schema,
passportLocalMongoose = require('passport-local-mongoose');

var Order = require('./order');
var Customer = new Schema({
    name: String,
    telephone: Number,
    address: String,
    email: String,
    seller: String
});

Customer.post('remove', function(next) {
    Order.remove({ customer: this._id }).exec();
    next();
});

Customer.plugin(passportLocalMongoose);

module.exports = mongoose.model("Customer", Customer);

And this is my customer route:

var express = require('express');
var router = express.Router();
var passport = require('passport');
var isAuthenticated = require('./isAuthenticated');
var Customer = require('../models/customer');
var Order = require('../models/order');

// (...)

router.delete('/:customer_id', function(req, res) {
    Customer.remove({ _id: req.params.customer_id }, function(err) {
        if (err)
            res.json({ SERVER_RESPONSE: 0, SERVER_MESSAGE: "Error deleting", ERR: err });
        else res.json({ SERVER_RESPONSE: 1, SERVER_MESSAGE: "Customer deleted" });
    });
});

// (...)

I did look this question and Mongoose Docs (Mongoose Middleware) but it's still unclear to me. I don't know what I'm missing or doing wrong.

Thanks in advance!

EDIT

This is my project's repository. Please, feel free to look into.

Upvotes: 3

Views: 12588

Answers (2)

alexhzr
alexhzr

Reputation: 153

I finally found the solution to this. Middleware wasn't firing because you must use remove(), save(), etc on model instances, not the model itself.

Example:

Customer.remove({...}); won't work.

Customer.findOne({...}, function(err, customer) {
  customer.remove();
});

will work and will do whatever is in Customer.post('remove').

Upvotes: 8

Sven
Sven

Reputation: 5265

Seems like this is the part you're focusing on:

Customer.post('remove', function(next) {
    Order.remove({ customer: this._id }).exec();
    next();
});

What you're doing wrong here is that the post hook is not given any flow control, so the next parameter is not actually a function but the document itself.

Change it up to this and you should get what you want:

Customer.post('remove', function(doc) {
    Order.remove({ customer: doc._id }).exec();
});

From the docs:

post middleware are executed after the hooked method and all of its pre middleware have completed. post middleware do not directly receive flow control, e.g. no next or done callbacks are passed to it. post hooks are a way to register traditional event listeners for these methods.

Upvotes: 1

Related Questions