Deleting multiple subdocuments and their related subdocuments with Mongoose

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.

Answer №1

Have you considered incorporating comments directly into posts? This way, when deleting a project in your code, you can first delete all the associated posts which include the comments. Once this process is successful, you can proceed to delete the project. This approach can significantly improve read performance by simplifying the retrieval of information - only one post document needs to be fetched instead of multiple documents for each post and its related comments.

While it is possible to embed posts within projects, depending on the volume and size of posts, it may be more beneficial to store them as separate documents to maintain scalability and efficiency. Consistency checks will be crucial in this scenario.

One option could be leveraging MongoDB's transaction feature, but considering the circumstances, eventual consistency might suffice without the need for transactions which are currently unstable. By removing all posts associated with a project before deleting the project itself and periodically checking for any inconsistencies, you can effectively manage data integrity.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The selected attribute does not function properly with the <option> tag in Angular

Currently, I am faced with a challenge involving dropdowns and select2. My task is to edit a product, which includes selecting a category that corresponds to the product. However, when I open the modal, the selected group/category is not displayed in the d ...

Adjusting HTML5 drag height while resizing the window

Code conundrum: var dragHeight = window.innerHeight - parseInt(jQuery("#drag_area").css("margin-top")) - 5;. It sets the drag height based on browser size, but there's a glitch. If I start with a non-maximized browser and then maximize it, the drag he ...

Is there a way to ensure that this ajax code functions seamlessly with all types of HTML files?

Currently, I am facing a challenge with an ajax call that retrieves data from a database, which I need to load into an HTML file. The issue lies in the fact that I have various HTML files and I am unaware of their contents. Despite spending countless hour ...

Can the installation of Canvas be done on a device with the M1 chip?

When attempting to install canvas on a MacBook Pro M1 using the command: npm install --save-dev canvas An error is displayed: npm ERR! code 1 npm ERR! path /Users/xiaoqiangjiang/source/reddwarf/frontend/js-wheel/node_modules/canvas ... (error message con ...

Passing PHP information into a JavaScript array

I am facing an issue with my PHP file where I am fetching data from a MySQL database and storing it in a PHP array. I am then trying to output this data as a JS array but for some reason, I am unable to access the JS variable in my JS files. Here is the c ...

Dealing with large integers in JSON when inserting them into a MongoDB database can be a complex task

Challenge : I am dealing with a highly intricate json file that contains integer values exceeding 8 Bytes (c_time, p_time), along with some smaller ones like id in the example below. Sample structure: { "c_time": 18446744062065078000 ...

Experiencing difficulties accessing the API route through Express

Every time I attempt to access /api/file, I am receiving a status code of 404. Here is the relevant code snippet: app.js : ... app.use("/api", require("./routes/users")); app.use("/api", require("./routes/file")); ...

Mobile version experiencing issue with Navbar not collapsing

The dropdown navigation bar on the mobile version of my website is not functioning properly. Despite several attempts, I have been unable to figure out a way to make it work effectively. <!DOCTYPE html> <html lang="en"> <head> & ...

Increasing values are applied to the text field when it is clicked or focused on

I have a grid with 18 rows of text fields, each requiring a unique ID. The bottom row may need ID 1 while the top row could need ID 15, depending on user choices. It doesn't have to be aesthetically pleasing, function is what matters. I plan to use th ...

Definition of TypeScript for caching middleware in Express

I recently came across a helpful Medium post that inspired me to create an express middleware function for caching the response. However, I'm facing some challenges while trying to implement it in typescript. Specifically, I am struggling to identify ...

How to automatically adjust select view in AngularJS as model value is updated

My select element is structured as follows: <select data-ng-model="transaction.category" class="form-control" data-ng-options="category.name group by category.parent for category in categories" required> </ ...

"Encountered a TypeError: Cannot read property 'params

I've encountered an issue with passing the id to my product page. Despite trying various solutions and searching for answers, I still can't get it to work. Below is my index.js code: import React from "react"; import {render} from &quo ...

Unable to add new tags in Vue multiselect component

Currently, I am utilizing a Vue Multiselect instance with two functions. One function interacts with the database to provide autocomplete functionality, which is working successfully. The second function allows for adding new tags that are not present in t ...

Using VueJS: Passing a variable with interpolation as a parameter

Is there a way to pass the index of the v-for loop as a parameter in my removeTask function? I'm looking for suggestions on how to achieve this. <ol class="list-group"> <li v-for="task in tasks" class="list-group-item"> ...

Tips for handling an empty jQuery selection

Below is the code snippet: PHP CODE: if($data2_array[7]['status'] == "OK"){ $degtorad = 0.01745329; $radtodeg = 57.29577951; $dlong = ($lng - $supermercado_lng); $dvalue = (sin($lat * $degtorad) * sin($superm ...

Array.from does not create a deep copy

I'm in the process of creating my own Battleship game, and I've been researching for about 10 hours but haven't been able to crack it yet. The issue I'm facing is related to making a deep copy using Array.from; whenever I modify the pl ...

Encountering a situation where the operation status is not defined while managing production errors

I am currently working on a Natours project where I aim to manage operational errors that may arise in both development and production environments separately. Below is the code for my appError.js: class AppError extends Error { constructor(message, sta ...

React: Assigning a unique className to an element in a list

In the code snippet below, I am attempting to add a className based on the state of the checkbox. While the className is being added correctly, the issue arises when it gets applied to all elements in the list upon checking/unchecking any checkbox. I aim ...

Is there a way to gradually reveal JSON data without continuously re-parsing and displaying it on a webpage?

Currently, I am working with a log file that is constantly updated by a running script in real-time. My goal is to effectively monitor the status of this script on a web page using HTML and JavaScript. To achieve this, I have utilized JavaScript to dynamic ...

Using jQuery to send LocalStorage data to an email address with the help of PHP

Currently, I am in the process of developing a basic eCommerce/checkout system. My goal is to utilize localStorage data and transfer it to PHP using jQuery or any other method that is convenient. However, when I attempted to send the email, I only received ...