Steps for updating a single field in multiple nested array documents using findOneAndUpdate

Having trouble updating a single value within a multi-nested array of documents using findOneAndUpdate.

The condition is as follows:

Update the warehouse amount where the productCode is "abc123", size "41" in warehouse "Hamburg".

Only getting back null or both sizes 41 and 42.

This is an excerpt from the document:

{
 "_id": ObjectId("xxxx636309f84479ec0c7b"),
 "productCode": "abc123",
 "brand": "Nike",
 "name": "aaa",
 "model": "Runner",
 "color": "Brown",
 "image": "shoe.jpg",
 "sizes": [{
   "_id": ObjectId("xxxxc636309f84479ec0c7e"),
   "size": "41",
   "wares": [{
     "_id": ObjectId("xxxx2c636309f84479ec0c80"),
     "ware": "Hamburg",
     "amount": 7
    },
    {
     "_id": ObjectId("5db72c636309f84479ec0c7f"),
     "ware": "Berlin",
     "amount": 7
    }
   ]
  },
  {
   "_id": ObjectId("5db72c636309f84479ec0c7c"),
   "size": "42",
   "wares": [{
    "_id": ObjectId("5db72c636309f84479ec0c7d"),
    "ware": "Hamburg",
    "amount": 16
   }]
  }
 ],
 "__v": 0
}

This is what has been attempted:

Product.findOneAndUpdate({
  "productCode": "abc123",
  "sizes.size": 41,
  "sizes.wares.ware": "Hamburg"
 }, {
  "$set": {
   "sizes.0.wares.amount": 99
  }
 }, {
  useFindAndModify: false
 },
 (err, products) => {
  if (err) {
   return res.status(422).send(err)
  }
  return res.json(products)
 }
);

Looking for a solution to this issue.

Answer №1

To meet the request of @ambianBeing, here is an example utilizing the findOneAndUpdate method:

Product.findOneAndUpdate({
    "productCode": "xyz789",
    "sizes": {
        $elemMatch: {
            $and: [
                { size: "38" },
                {
                    wares: {
                        $elemMatch: {
                            ware: "Paris"
                        }
                    }
                }]
        }
    }
}, {
    $set: {
        "sizes.$[theSize].wares.$[theWare].quantity": 75
    }
}, {
    arrayFilters: [{
        "theSize.size": "38"
    }, {
        "theWare.ware": "Paris"
    }]
})

Answer №2

Utilizing the filtered positional operator $[<identifier>] can efficiently handle nested array updates.

Mongo Shell Query:

db.collection.update(
  { productCode: "abc123" },
  { $set: { "sizes.$[outer].wares.$[inner].amount": 99 } },
  {
    arrayFilters: [{ "outer.size": "41" }, { "inner.ware": "Hamburg" }],
    multi: false
  }
);

Mongoose Model Query:

Product.update(
  { productCode: "abc123" },
  { "sizes.$[outer].wares.$[inner].amount": 99 },
  {
    arrayFilters: [{ "outer.size": "41" }, { "inner.ware": "Hamburg" }],
    multi: false
  },
  (err, rawDoc) => {
    if (err) {
      console.error(err);
    }
    console.info(rawDoc);
  }
);

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

"Implementing a Nested V-For Loop with Dynamic Styling

Need help binding an active class @click to a nested item in array of objects. The array looks like this: var arr = [ { "id": 10, "name": "Main Name 1" "parents": { "id": 1, "name": "Name1" } }, { "id": 11, "na ...

React Component for voting positively or negatively

I am working on creating a React component that contains an input field and two buttons. The input field should initially display the number 25. The component will have one button that decreases the count by 1, and another button that increases the count ...

JavaScript code to make titles slide in as the user scrolls

Looking for a better way to make all titles slide in upon scrolling instead of coding individually? Consider using a forEach loop! Here's how you can modify the code below: function slideInLeft() { document.querySelectorAll('.subtitle-left ...

The JSON data is being displayed as [object Object] when viewed in the console log

I'm fairly new to this community based on my post history, and I'm facing an issue with extracting the key and value from a JSON object. The output is not what I expected. Can someone point out where I am going wrong? (function($){ jQuery(do ...

Using Express and Dust.js to render a list of data items in a view

Currently, my homepage displays the 6 oldest Story posts from MongoDB. Here is the query I use to retrieve data from Mongo: var query = Story .find({maxlines:10}) .sort({_id:1}) .limit(6); After querying the data, I p ...

Building an email script using only JavaScript and the latest HTML5 features

Can an HTML5 and JavaScript contact form be set up to send responses via email? If so, what steps are involved in creating it? ...

What is the method for inserting a horizontal line into a highcharts js graphic?

add your own description This is the method to achieve it! I can accomplish this without using css positioning. ...

Is there a way to ensure one request completes before allowing another to be executed in Express/Node?

I am currently working on a task that involves fetching data from a third-party API (iTunes) to search for content provided by the API. The backend, which is handled by Express and Node, will interact with this third-party API. My goal is to trigger a POST ...

Disable touch interactions on the body, only allow pinch-zoom on specific elements

I have been attempting to implement the following code: body { touch-action: none; } .left-side { touch-action: pinch-zoom; } <div class="left-side"><img src="image.jpg" /></div> The touch-action: none is functioning properly, but ...

Remove the JSON key from all array elements while preserving their child elements

I have an array of JSON objects that looks like this: var array_json = [{"my":{"id":144,"price":12500000}}, {"my":{"id":145,"price":13500000}},{"my":{"id":146,"price":13450000}}, {"my":{"id":147,"price":11500000}},{"my":{"id":148,"price":15560000}}] My g ...

Ensure that the code is functioning properly for each element and is tailored to its specific date

Trying to implement a countdown using JavaScript and HTML elements. The code is functional, but encountering an issue with three items in the code: <div class="col-xl-4 col-md-6"> <article> <div class=&qu ...

"How can I display validation errors for email and fax in each row of loop items using Angular? Specifically working with Angular 8

In my Angular8 project with Bootstrap, I have created input fields dynamically from an array using a loop. When there is a validation error for the email or fax number input, the error is displayed. However, I noticed that if there is an error in the first ...

"Enhance your Highcharts experience with dynamic visualization and maximize the number of

When creating dynamic highcharts, I utilize the series.addPoint method. While it successfully adds points, the chart does not move as shown in this example - jsfiddle. This results in potentially having 100 points on the screen. How can I limit the displ ...

Storing props in JSX components using variables in React.jsLearn how to set props in JSX components and

If I have already created a component: class Co extends React.Component { render = () => { const name = this.props.name; return ( <p>Hello, my name is {name}</p> ) } } and stored it in a variable ...

Capturing the submit button using JavaScript and checking its presence with PHP's isset function

Appreciation is extended to all users of the site who take the time to respond to my inquiry. The main aim of my question, as indicated by the title, is to capture the form submission in JavaScript using the traditional PHP isset method. Sample Code: < ...

Exploring various templates with AngularJS Directives

Let's delve into a slightly complex topic, but I'll simplify it as much as possible for you. There is a directive in play: .directive('configuratorRows', function () { return { restrict: 'A', scope: { ...

Blending AngularJs Widget with Adobe Captivate for Enhanced Interactivity

I've encountered an issue with integrating AngularJs into Adobe Captivate 8, and I'm starting to question the compatibility between AngularJs and Captivate. Despite having correct design setups in Captivate, I'm uncertain whether the error l ...

The color type input is not responding to the onChange event

I have been searching a lot and exploring answers on Stack Overflow, yet I have had no luck. I am trying to retrieve the color value when the color is changed in an input field. Here is the code I am using, could you please assist me in finding out why it ...

Investigate the existence of a specific string within numerous arrays across a document within a MongoDB database

My objective is to create a query where I can input an _id and country name, and receive a true or false value indicating whether the given country is present in three arrays. For example, if I enter country:France and _id:5e4d18bd10e5482eb623c6e4, the exp ...

express-session is failing to maintain persistence and refusing to transmit a cookie to the browser

I am currently developing a web application using the MERN stack (React, Node.js, Express, and MongoDB). I have integrated express-session in my Node.js project, but for some reason, I cannot see the connect.sid cookie in the browser. Additionally, it appe ...