3

Company collection:

{
  "_id": {
      "$oid": "594196a685d5c72f00517f64"
  },
  "name": "company",
  "reports": [
      {
          "$oid": "5942afb5314f0235d9a3a302"
      },
      {
          "$oid": "5942b1641b10b236075bcd89"
      }
  ],
}

I understand I have to use update $pull to remove an element from reports.

How would create the query to achieve this?

I have this so far,

 var Company = require('../models/company');
 Company.update(
   { _id: company},
   { $pull: {'reports': report._id} }
 )

Is there a way to remove reports from this company automatically if I delete a report?

For example, instead of having to use update() on Company after a report is deleted, it would be nice if I can just do remove() on a report and Company should know it was deleted. (I come from a rails background so this is annoying)

Neil Lunn
  • 148,042
  • 36
  • 346
  • 317
Eric Chu
  • 1,649
  • 3
  • 20
  • 26
  • Are you using Mongoose? If so, what you're looking for is a [cascade delete](https://stackoverflow.com/a/14349259/1022914). My only concern is the way you store your report references. Why is it an array of objects opposed to an array of `ObjectIds`? The latter makes it easier to pull. – Mikey Jun 15 '17 at 17:59
  • @Mikey I am storing them in `ObjectIds` this is just how mLabs display them. Thanks! cascade delete is exactly what I was looking for @OmriLuzon but I'm using express and angular :( LOL sorry. – Eric Chu Jun 15 '17 at 18:22
  • @EricChu Take note that if you set a `'remove'` hook, it will be fired when you call `myDoc.remove()`, not when you call `MyModel.remove(query, callback)`. – Mikey Jun 15 '17 at 18:44

0 Answers0