Extracting Data from a Highly Nested Document in Mongoose

I am facing a challenge in deleting a deeply nested location object from the locations array. Even after carefully following mongoose documentation, my attempts have not yielded successful results:

lists = [{
  "listName": "Test",
  "_id": "8d55f0afe545a0178c320706",
  "listId": "5fd9a3bef6c39b2f9c4df65b",
  "date": "12/15/2020",
  "dueDate": "2020-11-18",
  "items": [
    {
      "itemNumber": 123,
      "description": "item123",
      "onHand": 60,
      "_id": "13dd1f26ecd2baeb61b3b455",
      "locations": [
        {
          "locationName": "loc1",
          "count": 10,
          "_id": "50a2c969465ba8010bd48977"
        },
        {
          "locationName": "loc2",
          "count": 20,
          "_id": "51c2f1d25311dc8fabdbf604a59b"
        },
        {
          "locationName": "Loc3",
          "count": 30,
          "_id": "7cb0c1f51a91c384846d65f8b2ae"
        }
      ]
    },
    {more lists}

Here is an attempt I made:

router.post("/lists/deleteLoc", (req, res) => {
      const {
        listId,
        list_id,
        item_id,
        location_id
      } = req.body;
      List.updateOne({
            "lists.listId": listId,
            "lists._id": list_id
          }, {
            $pull: {
              "lists.$.items": {
                locations: {
                  $elemMatch: {
                    _id: location_id
                  })
                .then(() => res.json({
                  msg: "location removed"
                }))
                .catch((err) => res.status(400).json({
                  msg: "Error: " + err
                }));
              });

If the specified location_id in the request was "7cb0c1f51a91c384846d65f8b2ae", it should delete the last location object from the array. The intended outcome is:

lists = [{
  "listName": "Test",
  "_id": "8d55f0afe545a0178c320706",
  "listId": "5fd9a3bef6c39b2f9c4df65b",
  "date": "12/15/2020",
  "dueDate": "2020-11-18",
  "items": [
    {
      "itemNumber": 123,
      "description": "item123",
      "onHand": 60,
      "_id": "13dd1f26ecd2baeb61b3b455",
      "locations": [
        {
          "locationName": "loc1",
          "count": 10,
          "_id": "50a2c969465ba8010bd48977"
        },
        {
          "locationName": "loc2",
          "count": 20,
          "_id": "51c2f1d25311dc8fabdbf604a59b"
        }
      ]
    },
    {more lists}

I have tried various approaches, but unfortunately, none of them have proved to be successful.

Additionally, I am uncertain about whether using a router.post or an axios.post request for deletion is appropriate. Should I consider using axios.delete and router.delete instead?

Answer №1

This method was successfully implemented in one of my similar databases!

List.updateOne({ "listId": yourListId },
        {
            '$pull': {
                'items.$[item].locations': { "_id": yourLocationId }
            }
        }, {
        "arrayFilters": [
            {
                "item._id": yourItemId
            }
        ]
    }, function (err) {
        if (err) {
            res.json(err)
        } else {
            res.json({ message: "Updated" })
        }
    })
}

Make sure to input the specific values from your database for the object you wish to remove.

For instance, to remove an object with

"locationname" : "Loc3"

You will need to use

var yourListId = "5fd9a3bef6c39b2f9c4df65b";
var yourItemId = "13dd1f26ecd2baeb61b3b455";
var yourLocationId = "7cb0c1f51a91c384846d65f8b2ae";

Give it a try!

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

Obtain asynchronous result from updating state in React

I am trying to achieve the following: myFunction = () => { this.setState( state => { const originalBar = state.bar; return { foo: "bar" }; }, () => ({ originalBar, newBar: state.foo }) //return this object ...

Sending data from one JavaScript file to another (a unique scenario)

I am facing an issue with passing a Javascript variable from one file to another within a Jquery document function. chat.js $(document).ready(function () { var a = "something" } to scripts.js $(document).ready(function () { console.log(a); //g ...

Tips for assigning a class to a div based on the route in Angular

In my angular template, I have a basic ng-repeat with some div elements. Now, I am looking to add a class to a specific div if the $routeParams.userId matches the id of the object in the loop. You can refer to the second line of code below for clarificatio ...

Retrieve all items pertaining to a specific week in the calendar

I'm trying to obtain a list of week ranges for all data in my MongoDB. When a week range is clicked, only the records for that specific week range should be displayed. By clicking on the week range, the ID of the week (let's say 42, representing ...

Instructions for inserting an anchor tag into the middle of a <p> element utilizing document.createElement("p")

When generating elements dynamically with JavaScript using document.createElement("p"), I am looking to create a paragraph element <p></p> that includes an anchor tag in the middle, creating a clickable link within the text. I aim to use JavaS ...

What is the best way to display two radio buttons side by side in HTML?

Looking at my HTML form in this JSFiddle link, you'll see that when the PROCESS button is clicked, a form with two radio buttons appears. Currently, they are displayed vertically, with the female radio button appearing below the male radio button. I& ...

Searching for true values in MongoDB using the query syntax can be challenging

I have a question that might be a bit embarrassing, but I need help with rendering a user search based on both location and date. Our profile object is structured like this: availability: { monday: { type: Boolean, default: false }, tuesday: { type ...

The Hidden Power of jQuery: Unleashing the Full Potential of .text()

I'm trying to make two values equal, but it's not working... var rowID = $("#@idSelectObjectGuid").val(); $($(".ls-grid-body tr").children("<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="240a64524770454648410a74564d ...

Controlling the Quantity of Selected Checkboxes with JavaScript

I am facing an issue with implementing multiple checkboxes with limits in JavaScript, as shown below. $(".checkbox-limit").on('change', function(evt) { var limit = parseInt($(this).parent().data("limit")); if($(this).siblings(':checked&ap ...

Determining if all neighboring elements are present in a multidimensional array using PHP

At work, we encountered a small problem that some of us have solved differently. We are now looking for a more efficient solution. To simplify the example, let's consider a multidimensional array with the following values: 0a00 000b c000 In this ...

Utilizing jQuery or Javascript to obtain the title of the current webpage, find a specific string within it, and then apply a class to the corresponding element

Let's imagine I start with this: <title>Banana</title> and also have some navigation set up like this: <ul id="navigation"> <li> <a href=#">Banana</a> </li> </ul> Upon loading the sit ...

Exploring the Combination of Conditional Rendering and Redux within the App.js File

Currently, I am in the process of setting up an authentication flow with Redux in my application. To control the display of either the app screen or the authentication screen, I have implemented conditional rendering in my App.js file. Here is the snippet ...

unable to access Realm with mongodb synchronization

I'm encountering difficulty opening a Realm due to issues with my setup. Below is the code snippet from my app: var configuration = user.configuration(partitionValue: "user=\(user.id)") configuration.objectTypes = [User.self] Realm.asyn ...

displaying the outcomes of each roll, including wins and losses

Currently I am diving into the world of C++ and feeling a bit perplexed about a specific task. My project involves creating a simulation of the CRAPS gambling game, with the desired output being the number of games won and lost on each roll. ____ games wo ...

Showing a header 2 element just once using both *ngFor and *ngIf in Angular

I have an array of words with varying lengths. I am using ng-For to loop through the array and ng-if to display the words based on their lengths, but I am struggling to add titles to separate them. Expected Outcome: 2 letter words: to, am, as... 3 lette ...

Sustaining the Status of a Changeable Form Element

To fulfill the requirement of constructing a Form Builder component that generates forms based on JSON data from the backend, I have identified 7 types of input fields that may be encountered: email password select file date input of type text input of ty ...

Inconsistency in the stacking of array variables in C code

A curious issue arises with the code below: makefile all: gcc main.c -o main; build example ./main 3 5 6 9 main.c #include <stdio.h> #include <stdlib.h> #include <limits.h> int main(int argc, char **argv) { if (argc < 1) { ...

Finding the maximum value among multiple variables in AngularJS

After performing calculations, I have assigned specific values to variables. console.log("Gain_weight is "+ Gain_weight); console.log("Gain_smoking is "+ Gain_smoking); console.log("Gain_exercising is "+ Gain_exercising); console.log("Gain_foodhabits ...

An algorithm for determining the frequency of an element within an array with a time complexity of O

Is there an efficient algorithm that can determine if a certain frequency percentage of array elements exists in an array of length n, all in linear time? While selection sort is O(n^2) and the majority algorithm has a time complexity of O(n), it can only ...

Vue.js computed property: [Vue warn]: Oops, looks like there's a hiccup in the render! Error: "TypeError: Unable to access property 'userId' of an undefined variable"

Just trying my hand at Vue.js, so bear with me if this seems too simple. I've got the code for Home.vue here: <template> <div class="home"> <div> <b-table striped hover :items="borrowingHistroy"> ...