Removing an item from an array within subdocuments when a nested id is located

{
    "_id" : ObjectId("55a4b23636e6ba35079eb497"),
    "userName" : "David",
    "email" : "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="e28683948b86a2858f838b8ecc818d8f">[email protected]</a>",
    "image" : "https://lh5.googleusercontent.com/-ivBeNFeatn4/AAAAAAAAAAI/AAAAAAAABkk/aa86ghW9VRg/photo.jpg?sz=50",
    "trade" : [ 
        {
            "selectedCar" : {
                "model" : "Mikecar",
                "year" : 77878,
                "condition" : "hkjhkj",
                "color" : "hkjhjkhjkhjk",
                "_id" : "55a4b22d36e6ba35079eb496",
                "imageUrl" : "http://cliparts.co/cliparts/Big/Kkz/BigKkzggT.png",
                "userName" : "josh Smith",
                "email" : "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="573d38243f17303a363e3b7934383a">[email protected]</a>"
            },
            "myCar" : {
                "model" : "Son90098",
                "year" : 879,
                "condition" : "kjhjkhkhj",
                "color" : "khjhjkhjk",
                "_id" : "55a4b24036e6ba35079eb498",
                "imageUrl" : "http://cliparts.co/cliparts/Big/Kkz/BigKkzggT.png"
            },
            "myEmail" : "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="bbdfdacdd2dffbdcd6dad2d795d8d4d6">[email protected]</a>"
        },
    "__v" : 2
}



User.findOneAndUpdate({'trade.myCar._id' : req.body.myCar._id }, {$pull: {'trade.$': {'trade.myCar._id' : req.body.myCar._id }}}, function(err,trade){
})

I need assistance in locating the nested id of an item within the embedded array trade and removing all items where

trade.myCar._id = req.body.myCar._id
. The objective is to eliminate the entry that includes both the objects selectedCar and myCar

Answer №1

To return the modified document using "new" and the argument for only the "inner" name in $pull:

User.findOneAndUpdate(
   { "trade.myCar._id" : req.body.myCar._id }, 
   { "$pull": {
       "trade.$": { "myCar._id" : req.body.myCar._id }
   }},
   { "new": true },
   function(err,trade) {

   }
})

Please note: The entire array element is removed as requested. If you want to just remove "myCar", then use $unset:

User.findOneAndUpdate(
   { "trade.myCar._id": req.body.myCar._id }, 
   { "$unset": { "trade.$.myCar": "" }},
   { "new": true },
   function(err,trade) {

   }
})

In this scenario, the array element remains intact, but the key is removed from that element.

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

Unveiling the Magic: Displaying Quill's raw HTML in Vue.js

Within my Vue.js app, I am utilizing the Quill editor to generate raw HTML content that is saved directly to the database without any cleaning. When fetching this content from the backend, the text and styling are displayed correctly (colors, bolding, etc. ...

Callback function not being triggered in Jquery's getJson method

I am currently faced with a javascript conundrum. Below is the snippet of code that I have been working on: $.get("categories/json_get_cities/" + stateId, function(result) { //code here }, 'json' ); ...

Encountering a React JSX issue when looping through an object

I am working with a JS object called myFieldsObj, which looks like this; { field1: {value: 1}, field2: {value: 2}, field3: {value: 3} } Within my JSX code, I am trying to iterate over this object and display some content. <MyCustomDialog> ...

A handy tip for sending a response once a for each loop has finished executing

It is important that Response.json executes only after the foreach loop has completed its execution. var todoarr = (req.body.data) ? req.body.data : undefined todoarr.forEach(function(element) { if(element.done == true) { TodoS ...

"Utilize jQuery to create a dynamic animation by togg

Looking for guidance on how to add animation to gradually reveal the answer? Provided my code below. Any assistance in making this functional would be greatly appreciated. <div class="q-a-set"> <div class="licensing-question" id="q_1"> <i ...

Steps for customizing the dropdown arrow background color in react-native-material-dropdown-v2-fixed

Currently, I am utilizing react-native-material-dropdown-v2-fixed and I am looking to modify the background color of the dropdown arrow. Is there a way for me to change its color? It is currently displaying as dark gray. https://i.stack.imgur.com/JKy97.pn ...

Error encountered when attempting to add document to Firebase database: admin:1. An unexpected FirebaseError occurred, stating that the expected type was 'Na', but it was actually a custom object

I am encountering an error when trying to add a document to my collection in Firebase. I have successfully uploaded an image to Storage and obtained the URL, but this specific step is causing issues. I have followed the code implementation similar to how F ...

Obtaining the Camera's Position Relative to the Origin in Three.js

The wording of this question might be unclear, but I'm struggling to phrase it concisely. Here's the scenario: there is a perspective camera in the scene along with a mesh. The mesh is positioned away from the origin of the axis. The camera is ...

Building a simple messaging platform with the power of Socket.io and Node.js

After following the guide at http://socket.io/get-started/chat/, I attempted to create a basic chat application. However, upon running npm install --save socket.io I encountered the error message below. How can I resolve this issue? npm WARN package.jso ...

Utilizing additional JavaScript libraries with custom Power BI visuals

Seeking clarification on how to use the d3 library within my visual.ts file. I have installed it using npm and added it to the externalJS section of pbiviz.json, but I am unsure of any additional configurations needed to successfully include and utilize it ...

Attempting to configure a discord bot. Can anyone help me identify the issue?

I've been working on setting up a discord bot using Discord.js. I have all the necessary tools installed - Node.js, Discord.js, and Visual Studio Code. I've even created an application and obtained a token for my bot. However, I'm running in ...

Implementing inline styles in the HEAD section of a Next.js website

I currently have a blog hosted on Jekyll at , and I'm looking to migrate it to Next.js. My unique approach involves embedding all the styles directly into the HEAD element of each HTML page, without utilizing any external stylesheet files. However, wh ...

Accessing child value in parent component using React.js

In my project, I have a main Component called [MainLayout] which contains a child component called [ListItems]. The [ListItems] component further has multiple children components called [ListItem]. I am trying to figure out how to extract the value of the ...

Guide on dividing and presenting ajax information into two separate div containers

I am attempting to showcase two sets of data on separate divs using ajax. Below is the code I am utilizing for this task. Here is the ajax implementation $(function () { $(".myBtn").click(function () { var id = $(this).data("id"); ...

A method to efficiently send multiple axios GET requests by incrementing the URL parameters

Is there a way to efficiently send multiple HTTP GET requests using Axios? For instance: let maxRequests = 3000; let currentRequest = 0; do { currentRequest = currentRequest + 1; await response = axios.get(`https://example.com/${currentRequest}` ...

Troubleshooting problems with the jQuery 'Add row' function counter

Recently, I encountered an issue with a simple form on my website. The problem arises when I click the 'Yes' radio button and then click 'Add 1 more' multiple times. Instead of adding the desired 4 rows, I end up with around 9 rows. Qu ...

Is there a way to exclude certain URLs from the service worker scope in a create react app, without the need to eject from the project?

Is there a way to remove certain URLs from a service worker scope in create-react-app without needing to eject? The service worker is automatically generated, and it seems impossible to modify this behavior without undergoing the ejection process. ...

Switch the active function from click to load

I'm looking to automate a function that checks for mobile internet connection. Currently, the function is triggered by clicking something (OnClick Function), but I want it to run automatically when the app launches! How can I achieve this? This is ...

Collaborating and monitoring data between controllers

A unique challenge has arisen as we implement a tree-style navigation element that must communicate with other directives/controllers. The main objectives are: Keep track of the current selection, Detect when the row selection changes. The task at hand ...

Building a Friendship Connection System using Express and MongoDB

I have the task of implementing a feature that allows users to send friend requests similar to Facebook and other social media platforms. While I have started creating this functionality, my progress has been hindered by my lack of experience with mongoDB ...