0

First of all, this code works but I just want to make sure it is correct. Is this the proper way of removing referenced data when using mongoose?:

  router.delete("/clients/:client_id/domains/:domain_id", function(req,res) {
    Client.findById(req.params.client_id).populate("domains").exec(function(err, client) {
      Domain.remove({_id: req.params.domain_id}, function(err,dom) {
        client.domains.remove({_id: req.params.domain_id});
        client.save(function(err) {
          console.log(err);
        });
      });
    });

    res.redirect("/");
  });

Can I somehow automatically remove it from referenced and populated domains array or do I have to first remove it by calling remove on a model and then pulling it from array like in the example above? Thanks for your help in advance.

thyforhtian
  • 366
  • 3
  • 9
  • Possible duplicate of http://stackoverflow.com/questions/14348516/cascade-style-delete-in-mongoose – JohnnyHK Jun 23 '14 at 21:58
  • @JohnnyHK The middleware is a very good idea. But what confuses me is a mongoose documentation which says: _The documents returned from query population become fully functional, removeable, saveable documents ... Take caution when calling its remove method because you'll be removing it from the database, not just the array._ So I understand it is just enough to call remove of the populated document and it is completely removed from the database. But when I did that (I guess incorrectly) it got removed from arrat but stayed in db. – thyforhtian Jun 24 '14 at 05:57

0 Answers0