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();
});