Objective: Remove all soft items from array stored in MongoDb using Mongoose

I have a unique Array property in my document that is filled with lovely fluffy objects. Now, I am looking to remove all objects within a specific range -> qdate:20210225.

The property in the database is named weeks and appears as follows:

[
    {
        "time": [
            "06",
            "00"
        ],
        "active": false,
        "reason": "",
        "bookTime": "202102250600",
        "qdate": 20210225,
        "booked": false
    },
    ...

I attempted to delete one of these fluffy objects, but others remain unaffected. I tried different combinations like this:

const company = await Company.updateMany(
    { email: 'example@email.com' },
    { $pullAll: [{ 'weeks.qdate': 20210225 }] },
    (err, data) => {
      if (err) console.log(err);
    }
  );

 const company = await Company.updateMany(
    { email: 'another@example.com' },
    { $pullAll: [{ 'weeks': { $elemMatch: { qdate: 20210225 } } }] },
    (err, data) => {
      if (err) console.log(err);
    }
  );

I understand that from a query I can only pull one occurrence, so I could find just one object matching the value of qdate:20210225. I attempted an aggregate pipeline to get all occurrences, but I could only replace values, not delete entire objects.

Can someone please help me out?

Answer №1

It seems like utilizing the $pull operator could be the solution to your issue:

By using the $pull operator, you can eliminate all occurrences of a specific value or values that meet particular criteria within an existing array.

Consider implementing the code snippet below for potential assistance:

const organization = await Organization.updateMany(
  { email: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="aedacbdddaeec9c3cfc7c280cdc1c3">[email protected]</a>' },
  { $pull: { weeks: { qdate: 20210225 } } },
  ...
);

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

Is it possible to continuously update a Google line chart by programmatically adding rows at specific intervals using an AJAX call

Is there a way to dynamically add rows to the Google line chart each time data is retrieved via an AJAX call at set intervals? This is the existing code: google.charts.load('current', {'packages':['line']}); google.charts. ...

What are the benefits of removing event listeners in Reactjs?

In my opinion, the event listeners need to be reliable and consistent. React.useEffect(() => { const height = window.addEventListener("resize", () => { setWindowSize(window.innerHeight); }); return () => window.remov ...

Activate a button on-the-fly

When the page loads, I have an empty array. Since there are no values stored in this array, I disabled the button using ng-disabled="array1.length==0". Now, on the page that opens up, there are four drop downs present. My goal is to enable the button once ...

Redis Integration with MongoDB

I have a basic Express application, and my routes are organized in the index.js file as shown below: var user = require('../models/user'); exports.index = function(req, res){ res.render('index', { title: 'Express', object: ...

Unable to redirect page in Codeigniter after submitting button

I am facing an issue with inserting and updating data in my database using Ajax to my controller. Despite the data being inserted and updated accurately after clicking the button, the changes are not reflected on my view page until I manually refresh it. A ...

Is there a way to mask all communication with the bot and only display the ultimate outcome in Element Web Messenger?

I've been experimenting with the Matrix Element Web Messenger and came across a bot on GitHub (mautrix/whatsapp) that enables connection to Whatsapp. Rather than the traditional process of creating a room, sending a "login" message, and receiving a QR ...

Is there a way to determine the position of the highlighted text within a textarea?

Is there a simple way to calculate the position of the selected text within a textarea using vanilla JavaScript or Angular (possibly with a directive)? This is important in order to display a div with a popup above the selected text. Coordinates are need ...

Transferring variables from EJS to JavaScript on render (server to client) securely to prevent cross-site scripting vulnerabilities

When passing variables to JavaScript using ejs, the accepted method often looks like this: <script> var foo = <%- JSON.stringify(foo) %>; </script> However, there have been issues with XSS vulnerabilities using this approach. Is there ...

Changes are being made to the Redux state without triggering any dispatch actions

I am facing an issue in my react + redux app, specifically in the editing form section. Problem Description Click on the "edit" button to modify a document The edit form is displayed Edit or delete a value within the form Instead of saving the changes ( ...

When using the transition mode "out-in" in Vue, the returned ref element may be undefined

Encountering an issue where when mode="out-in" is used in a <transition mode="out-in">, a ref'd element returns undefined during the `updated` lifecycle. Strangely, it works fine without the `mode="out-in"` attribute. Any suggestions on how to ...

Why does AngularJS $watch only execute once?

Why do the codes in the watch only run once? How can I address this issue? this.$rootScope.$watch('tabType', () => { if (this.$rootScope["tabType"] === TabType.Sent) { this.$scope.refreshSentList(); } else if (this.$rootScope[ ...

JavaScript function trying to send a POST request to API

I'm encountering an issue when attempting to execute an API GET request using JavaScript's built-in XMLHttpRequest function. I'm perplexed by why this functionality is failing to operate properly. function getStats(username){ const request ...

Error encountered: Cannot load Bootstrap date time picker in MVC due to ReferenceError: $ is not defined

My issue arises when trying to incorporate the bootstrap date time picker - the calendar fails to load upon clicking on the "glyphicon glyphicon-calendar" icon. Despite adding all necessary files, an error persists: Uncaught ReferenceError: $ is not de ...

When attempting to append a script element and the operation fails due to lack of authorization, which error is typically thrown

I am trying to handle a particular failure in this JavaScript code: var script = $wnd.document.createElement('script'); script.setAttribute('src', url); script.setAttribute('type', 'text/javascript'); When the URL ...

Is there a way to detect when the browser's back button is clicked?

As I work on supporting an e-commerce app that deals with creating and submitting orders, a user recently discovered a loophole wherein they could trigger an error condition by quickly pressing the back button after submitting their order. To address this ...

Separate the divs in a template into individual templates, or alternatively, utilize ng-if to display different divs within a single template

As a newcomer to AngularJS, I am seeking advice on the most efficient way to code for the given scenario: Scenario: I have a single HTML template containing multiple divs, and I need to display only one div at a time based on specific conditions. Two app ...

The challenge of loading multiple objects asynchronously in three.js

When I try to load multiple models onto the same scene simultaneously, only one model is successfully loaded. For instance, if I have a building scene with various objects like chairs and toys inside, only one object gets loaded when I try to load them all ...

Guide to utilizing various MongoDB databases in Spring while executing JUnit test cases

Currently working on testing Spring Boot (2.0) using JUnit5 and looking to switch to a different database for unit tests. Is there a way to determine if the Spring app is being launched by JUnit or not? I intend to implement this in the AbstractMongoCo ...

What steps should I follow to create a JavaScript file incorporating jQuery?

As a newcomer to JavaScript and JQuery, I come from a background in basic C++ where I enjoy including header files and calling functions from there to maintain clean code. Now that I want to create a new JavaScript file, how can I ensure that I am able to ...

Guide to displaying a partial in the controller following an ajax request

After initiating an AJAX request to a method in my controller, I am attempting to display a partial. Below is the AJAX call I am currently using: $('.savings_link').click(function(event){ $.ajax({ type: 'GET', url: '/topi ...