0

I have written an app in nodejs + mongodb, in my app I have two models, both relate and what I need it is that when I delete a document from mongo automatically delete documents that are referred to within it ...

User model:

var userSchema = new mongoose.Schema({
  'email': {type: String, unique: true},
  'password': String,
  'name': String,
  'phone': String,
  'photos': [ { type: mongoose.Schema.Types.ObjectId, ref: 'Photo' } ],
  'createdAt': {type: Date, default: Date.now}
});

Photo Model:

var photoSchema = new mongoose.Schema({
  'image': String,
  'description': String,
  'uploadedAt': {type: Date, default: Date.now},
  'uploadedBy': {type: mongoose.Schema.Types.ObjectId, ref: 'User'}
});

I just need the simplest way for a user to be removed when all documents belonging to it model photos are deleted.

I'm looking for a simpler or easier way, as currently would:

UserModel.findByIdAndRemove(req.params.id, function(err, response) {
  PhotoModel.find({'uploadedBy': req.params.id}).remove().exec();
});
Rodrigo Moreno
  • 629
  • 9
  • 24
  • 1
    There's the [`cascading-relations`](https://github.com/jraede/cascading-relations) plug-in (no experience with it myself), but that will basically do the same thing. Also, check out [this post](http://stackoverflow.com/a/14349259/893780). – robertklep Jul 17 '15 at 07:04
  • Isn't your example deleting users before the photos? Your question seems to be asking, how can you automatically delete a user when user.photos.length = 0. Is this correct? – Yousef Jul 17 '15 at 08:20

0 Answers0