Banana: Eliminate linked IDs using purgeMany trigger

Here is an example of my schema structure:

const Author = new Schema({
    name: String,
    posts: [{ type: mongoose.Schema.Types.ObjectId, ref: "Post" }]
});

const Post = new Schema({
    text: String,
    author: { type: mongoose.Schema.Types.ObjectId, ref: "Author" }
});

What would be the most effective approach to remove ObjectId entries from the Author object when using deleteMany() to delete multiple posts?

I attempted to utilize a deleteMany pre hook, but it only provides information about the number of documents that were deleted and not the actual ObjectIds of the posts.

Answer №1

To efficiently delete multiple documents, you can first create a query object for the deletion process and use it to fetch the targeted documents using find. Once you have retrieved all the necessary documents, you can proceed to delete them using deleteMany.

If the count of deleted documents matches the total fetched document count, you can safely remove all references from the author's list. However, if the counts do not match, you will need to iterate through the initially-fetched documents, attempt to fetch each one again, and if it is not found, then it has been deleted and can be safely removed from the author.

Here is an example in TypeScript:

  const queryObj = { foo: 'bar' };
  const postsCollection = mongoDb.getCollection<{ _id: ObjectId }>('posts');
  const postsToDelete = await postsCollection.find(queryObj).toArray();
  const deleteManyResult = await postsCollection.deleteMany(queryObj);

  if (deleteManyResult.deletedCount === postsToDelete.length) {
    for (const deletedPost of postsToDelete) {
      // delete from author
    }
  } else {
    for (const potentiallyDeletedPost of postsToDelete) {
      const post = await postsCollection.findOne({ _id: potentiallyDeletedPost._id });
      if (!post) {
        // delete from author
      } else {
        // handle non-deleted post
      }
    }
  }

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

Highcharts plots only appear once the browser window is adjusted

Having some issues while testing out the Highcharts javascript charting library on a specific page. The problem I'm encountering is that none of the data appears until I adjust the browser's size slightly. Prior to resizing, the tooltip does dis ...

Utilizing jQuery to Perform Calculations with Objects

Can someone help me with a calculation issue? I need to calculate the number of adults based on a set price. The problem I'm facing is that when I change the selection in one of the dropdown menus, the calculation doesn't update and continues to ...

Leverage both props and destructuring in your Typescript + React projects for maximum efficiency!

Is it possible to use both destructuring and props in React? For instance, can I have specific inputs like name and age that are directly accessed through destructuring, while also accessing additional inputs via props? Example The desired outcome would ...

Filtering for Material Autocomplete is limited to the getOptionLabel field

Currently, I am utilizing the Google Material-UI autocomplete component. It is currently only filtering based on the "getOptionLabel" option field when text is entered into the input field. However, I would like the autocomplete to filter based on more tha ...

Exploring Nested Divs with Vue Test Utils

Recently, I came across this shallowMounted vue component: <div class="card p-relative"> <div class="card-header"> <div class="card-title h4"> a lovely title <!----> <!----> </div> </div ...

Initiate a cascade delete action without physically removing the data

Is there a method to reset a User record similar to a factory reset without actually removing the user record, but still triggering the cascading delete process? ...

Issue with setting innerHTML of element in AngularJS app upon ng-click event

Look at this block of HTML: <div class="custom-select"> <div class="custom-select-placeholder"> <span id="placeholder-pages">Display all items</span> </div> <ul class="custom-select- ...

Implement the insertion of ObjectId data into the response in a node/express application

While using postman to insert an ObjectId, I encountered an error when setting the Content-Type header to multipart/form-data. https://i.sstatic.net/NxUfv.png The error message I keep receiving is: { "errors": { "singer": { "mess ...

Unlocking the Power of refs in React's this.props.children

Wondering if it's possible to call a function of a child component in React by accessing refs from this.props.children. var ComponentSection = React.createClass({ componentDidMount: function() { // Need to find a way to access refs in this ...

What is the process for executing JavaScript code that is stored as a string?

After making an AJAX call, I receive a random string (constructed dynamically on the server) that contains JavaScript code like: Plugins.add('test', function() { return { html: '<div>test</div&g ...

Integrating an AngularJS service into a controller

Currently working on a straightforward AngularJS app that features a game, home view, and game over view. I've shared most of the code below: http://jsfiddle.net/Seasamh/5bqq1bj8/ Here are the html templates: home.html <span>This is the ...

The correct usage of && and || operators in javascript

I've developed a small web application and I'm facing an issue where I want to trigger an alert when the 'enter' key is pressed if there is an empty or space value. Currently, the alert appears not only on hitting 'enter' but ...

The emission from Socket.io is originating from the recipient's browser without being transmitted to the sender's browser

Hey there, I'm fairly new to socket.io and not completely sure if what I'm doing is the standard way, but everything seems to be working fine so I guess it's okay. I've been working on a chat application where messages are stored in a d ...

JQuery's is() function is returning a true value

I am facing a dilemma with a particular string that can either represent text or an anchor tag with text. I have implemented some logic to always return the text in the following way: $(text).is('a') ? $(text).text() : text; The idea behind ...

PHP - WebCalendar - Show or Hide Field According to Selected Item in Dropdown List

Working with the WebCalendar app found at to make some personalized adjustments to how extra fields function. I've set up two additional fields: one is a dropdown list of counties, and the other is a text field. Within the dropdown list, there is an ...

Modal containing react-select dropdown opens successfully

I am currently facing an issue with my custom modal that contains 2 react-select components. The modal body is set up to auto scroll when the content exceeds its size, but the problem arises when the dropdowns of the react-select components open within the ...

Guide to implementing if else statements with Protractor

I am facing some unusual situations and I'm not quite sure how to address them. As a newcomer to testing, I've been tasked with testing a website's cart function for proper functionality. The challenge arises when we add a certain number o ...

Verifying if a JavaScript textarea is empty

How can I make a textarea have a visible border around it when the string is empty, without needing to first input and delete text? Here is my current code: $("#message-box").on("keyup", function(){ var charCount = $("#message-box").val().length; ...

What is the best way to update data in Highcharts with Vue 3?

Issue with Updating Highcharts Data Using Vue.js 3 Within my Vue.js 3 web application, I have integrated a Highcharts Chart alongside some statistics display. This setup includes global buttons for time-filtering options such as All, Year, Month, and Week ...

What are the advantages and disadvantages of utilizing MongoDB on Elastic Beanstalk and establishing a connection with it?

My current setup involves a 3 tier application utilizing a Spring Boot REST API middle tier and a MongoDB backend on AWS. I am considering running the MongoDB Docker container in Elastic Beanstalk's single container option for scaling purposes. The p ...