In my MEAN-application (Angular2) I want to delete all referenced objects when deleting the object itself. I'm using Mongoose with the remove middleware. So my question.js file looks like this:
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var Answer = require('../models/answer');
var QuestionSchema = new Schema({
content: {type: String, required: true},
questionTxt: {type: String, required: true},
position: {type: Number, min: 0, required: true},
answers: [{type: Schema.Types.ObjectId, ref: "Answer"}],
followUpQuestions: [{type: Schema.Types.ObjectId, ref: "Question"}],
additionalInfoText: {type: String},
lastChangedBy: {type: Schema.Types.ObjectId, ref: 'User'},
lastChanged: {type: Date},
isRoot: {type: Boolean}
});
/**********************************************
* Deletes all answers and questions referenced by this question
***********************************************/
schema.post('remove', function(doc) {
var deletedQuestion = doc;
//code missing to find the answers and delete all referenced answers
});
});
module.exports = mongoose.model('Question', QuestionSchema);
I know I can find one by using:
Answer.findById(doc.answer, function(err, doc){});
I also now that I can use the find method to find more than one element and adding a query. But I just found stuff to find one specific id or to only delete them from the array. But I want the objects to be removed and not just the reference in that array.
If it's duplicated, feel free to close this question, but I didn't found the answer after googling, stack overflowing and in the related topics.
Thanks for your help!