Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongoose: Delete all referenced objects in an array when deleting referencing object

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!

like image 394
Brudus Avatar asked Jun 26 '16 14:06

Brudus


1 Answers

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


If you are interested to use a cascading delete, you can look into a npm module built for it. Cascading-Relations - Links NPM & Git

$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.

like image 162
Amol M Kulkarni Avatar answered Sep 20 '22 05:09

Amol M Kulkarni