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!
Why don't you simply add your own 'remove'
Mongoose middleware on the Question
schema to remove all other documents i.e. answers that references the question.
Example: In middleware function, you can do something like this:
QuestionSchema.pre('remove', function(callback) {
// Remove all the docs that refers
this.model('Answers').remove({ Question_Id: this._id }, callback);
});
$cascadeDelete defines whether or not deleting a document will also delete its related documents. If this is set to true, then all related documents will be deleted when the main document is deleted.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With