In my application, I have a Project document that contains an array of subdocuments structured as Tasks. Each Task has its own array of subdocuments with a schema called Comments.
const projectSchema = new Schema({
_id: Schema.Types.ObjectId,
name: { type: String, required: true, unique: true },
description: { type: String, default: '' },
tasks: [{ type: Schema.Types.ObjectId, ref: 'Threads' }]
});
module.exports = mongoose.model('Project', projectSchema);
const tasksSchema = new Schema({
projectId: { type: Schema.Types.ObjectId },
_id: Schema.Types.ObjectId,
title: { type: String, required: true },
text: { type: String, required: true },
comments: [{ type: Schema.Types.ObjectId, ref: 'Replies' }]
})
module.exports = mongoose.model('Tasks', tasksSchema);
const commentSchema = new Schema({
taskId: { type: Schema.Types.ObjectId },
_id: Schema.Types.ObjectId,
text: { type: String, required: true }
})
module.exports = mongoose.model('Comment', commentSchema);
My challenge is ensuring that when I delete the Project document, all associated Tasks and Comments related to that project are also deleted. To achieve this, I use findOneAndDelete method and create a post middleware to handle the deletion of all Tasks.
projectSchema.post('findOneAndDelete', function(doc, next) {
mongoose.model('Tasks').deleteMany({ projectId: doc._id }).exec();
next();
})
However, I am facing a dilemma on how to efficiently delete every individual Comment since deleteMany method returns an object with the operation's result. Should I iterate through each Task and call findOneAndDelete for every one before deleting their respective Comments? This approach seems inefficient especially when dealing with a large number of tasks.