I have a MongoDB database in which I have a topic, MCQs question, and true-false question schema. The topicId is present in the other two tables(MCQs and T/F). Now my question is if I delete the topic all the questions related to that topic in the other two tables should also be deleted. Just like a cascade in SQL but as I read MongoDB does not support cascade. I used some middleware after going through some tutorials but I am very new to MongoDB I could not figure that out. Can anybody please help me? I am really stuck with that problem.
Here is my topic Schema in topic.model.js file.
const mongoose = require(‘mongoose’);
const Schema = mongoose.Schema;
const True_false = require(‘…/models/true_false’);
const Mcqs = require(‘…/models/mcqs’);
const Open_Ended = require(‘…/models/open-ended’);
const topicSchema = new mongoose.Schema({
topic: {
type: String,
required: true
},
ageGroup: {
type: String,
required: true
},
grade: {
type: String,
required: true
},
noOfQuestions: {
type: String,
required: true
}
});
// I wrote this middleware but I do not know that it is correct and how to use it in the delete topic route.
topicSchema.pre(‘remove’, function(next) {
Mcqs.remove({topicId: this._id}).exec();
Open_Ended.remove({topicId: this._id}).exec();
True_false.remove({topicId: this._id}).exec();
next();
});
const Topic = mongoose.model(‘Topic’, topicSchema);
module.exports = Topic;
// My route in topic.route.js file
function topic_delete(req, res) {
Topic.findByIdAndRemove(req.params.id)
.then(data => {
if(!data) {
return res.status(404).send(‘Topic not found!’)
} else
return res.send(200).send(‘deleted’)
}).catch(err => {
console.log(err)
});
};
router.delete(‘/delete/:id’, topic_delete);
Right now with that API the topic is deleted but not the questions so it means that my middleware is not working. Can Anyone please help me that how can I use my middleware in my route file?