Updating MongoDB nested item by dynamic ID is a breeze

Hey there, I'm currently working on updating a nested Object in my MongoDB.

The current structure looks like this:

[
 {
  "_id": "5871010d1ff9831574e7178d",
  "created_at": "2017-01-07T14:54:05.791Z",
  "updated_at": "2017-01-07T14:54:05.791Z",
  "place_id": "ChIJ1eTO6eS1vkcRL_mX2RWUKo4",
  "name": "Kunstwerk Restaurant Gummersbach",
  "__v": 0,
  "cooks": [],
  "menus": [
   {
    "58727068ba8d6c04a0ea331f": [
      {
        "intolerances": {
           "intolerance" : "false"
            ...
          },
        "nutritiondata" : [
          {...}
         ],
         "cookname": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="5c28392f2837333f341c28392f28723839">[email protected]</a>",
         "menuname": "MenünameX"
      }
    ]
  }
]

The nested ID in the menus section is actually another ID of a MongoDB document that is generated dynamically.

I have been trying to update the "menuname" field, but I'm facing issues as MongoDB either returns null or doesn't find the element due to the need to search for only the key and not the key-value pair.

Here's what I have tested so far:

db.restaurants.update({ 'menus.58727068ba8d6c04a0ea331f', { $set : {"menus.$.menuname" : "test"}}});

db.restaurants.findOne({ 'menus.58727068ba8d6c04a0ea331f' : "58727068ba8d6c04a0ea331f"});

db.restaurants.find({ menus : { $elemMatch : {"58727068ba8d6c04a0ea331f": "58727068ba8d6c04a0ea331f" }}});

db.restaurants.findOne({ menus : { $eq : "58727068ba8d6c04a0ea331f" }});

Answer №1

To update the menu item, use the $set method in the following manner:

db.restaurants.update({"_id":"5871010d1ff9831574e7178d"}, {$set: {"menus.58727068ba8d6c04a0ea331f.0.menuname":"test"});

Ensure you know the index of the item in the array you are updating for this to work. Visit this Page for helpful examples on updating multi-level nested arrays. It could be beneficial to you.

Answer №2

Big shoutout to suzo for helping me crack the code. Here's the working MongoShell snippet:

db.restaurants.update({"_id" : ObjectId("5871010d1ff9831574e7178d")}, {$set: {"menus.58727068ba8d6c04a0ea331f.0.menuname" : "testName"}});

UPDATE: Dealing with a Mixed type field required some adjustments. Here's the revised correct code:

 Restaurant.findOne({ _id : req.body.r_id }, function(error, restaurant){
    if(error) console.log(error);

    for(var i = 0; i < restaurant.menus.length; i++){
          restaurant.markModified('menus');
        if(restaurant.menus[i][req.params.id] != undefined){
            restaurant.menus[i][req.params.id].menuname = req.body.name;
        }

        if(i == restaurant.menus.length-1){
            restaurant.save();
            res.json(jObj);
        }
    }

  })

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

Discover the Elements that have been incorporated through the use of JavaScript

I am facing an issue with my ASP site where users can add Label elements. The problem is I am not able to track the labels that were added or their IDs. All I know is that they will be inside the Panel called pnl_Added. Once the user has finished adding la ...

executing a hook within _app.tsx in Next.js

The issue I'm facing involves the rendering of a hook that helps determine if my components are within the screen's view to trigger animations. This hook is executed in _app.tsx, however, it doesn't run when switching to another page. Oddly ...

Developing a custom function to retrieve an array as a callback

I'm currently diving into the world of Node.js Struggling with implementing my own callback function in a certain method. It may seem like a straightforward task, but I'm finding it quite challenging to grasp. This specific function takes an ad ...

Duplicate values of React object properties when using .push method within a loop

In my code, I've implemented a function called handleCreate that is responsible for taking user data and inserting it into a database. Within the loop of aliasArr.forEach(), I am sending new user instances to my database for each element in the alias ...

Implementing Vue data binding with JavaScript objects

I have been tinkering with a JavaScript object that I want to connect with a Vue view. When I trigger a function to update this JavaScript object using AJAX, I expected Vue to automatically sync up and refresh the view. However, it seems like the binding ...

Numerous textareas fail to function properly according to JQuery's standards

Need help with resizing multiple textarea elements dynamically as the user types in them (on the Y-axis). Currently, I have code that successfully resizes a single textarea, but it does not work when there are multiple textareas on the page. Here is the c ...

Utilize underscore's groupBy function to categorize and organize server data

I am currently utilizing Angular.js in conjunction with Underscore.js This is how my controller is structured: var facultyControllers = angular.module('facultyControllers', []); facultyControllers.controller('FacultyListCtrl', [' ...

Resolving the Persistence Problem of Navigation Bar Fading In and Out

I've been struggling for hours trying different methods to achieve the desired outcome, but unfortunately, none of them have worked as expected. My goal is simple: I want the fixedbar to fade in when the scroll position exceeds the position of the ph ...

"Vue3 offers the ability to return a multi-layer object through the Provide-Inject

While implementing provide-inject in my personal project, I encountered an issue where the value returned by inject() was a RefImpl Object. This meant that I had to access the actual value using inject().value.value instead of just inject().value. Here is ...

What is the proper way to supply the `useUnifiedTopology: true` option to the constructor of my Node.js Mongoclient?

I'm trying to figure out how to include the useUnifiedTopology property in my MongoClinet constructor. Even though the constructor I'm using doesn't have a "new" keyword and is not formatted in the preferred way in the documentation, everyth ...

Display data in Highchart legend only if it has values

In a unique scenario, I am required to compare various items and display the results in a chart. The user inputs two, three, or four article IDs and receives the corresponding data displayed in a chart. The issue arises when the user enters only two or th ...

When the react autocomplete dropdown appears, it pushes other input elements downward, affecting their

Having implemented an autocomplete dropdown feature by following this link, I am encountering an issue with displaying the dropdown items. As shown in the reference link, the dropdown items are rendered within a div tag with the position set to relative. ...

alter URL parameters dynamically during API invocation

Is there a way to call an API multiple times in one request? I need the ability to dynamically adjust the date parameters for each call so that I can retrieve data for different days simultaneously. While conducting research, I came across the following c ...

The Gulp task abruptly terminates before the Stream has a chance to trigger the "end" event

const gulpJasmine = require('gulp-jasmine'); const gulpDebug = require('gulp-debug'); function runTest(platform, testType) { const timer = startTimer(); console.log('started!'); return gulp.src('./src/**/_test/**/ ...

Sharing JSON data with public/javascripts/X.js in Node/Express: A beginner's guide

Currently facing a challenge with my Express project. Take a look at https://github.com/MoreeZ/help1 and examine ./public/javascripts/budget.js. My goal is to swap the incomeData object to read data from ./incomedata.json I attempted passing it through th ...

Influence the behavior of surrounding elements as we move our cursor over them

I want to create an effect where I have two images, with the first one hidden initially. When we hover over the second image, the first image should become visible. Here are the codes and class names related to the images: <div class="entrycontent"&g ...

Exploring Vue's data binding with both familiar and mysterious input values

How can I model an object in Vue that contains both known and unknown values? The quantity is unknown, but the type is known. I need to present user inputs for each type, where the user enters the quantity. How should I approach this? data() { retur ...

What is the abbreviated term for personalized elements in React Native development?

After discovering that custom components can be created like this: const CustomComp=()=>{ console.log('Created custom comp'); return(<View></View>); } export default function App(){ return(<View style={{flex:1}}> &l ...

When using Node.js with Nginx, requests are timing out at the Nginx level before the processing is completed in Node.js

I have a setup where I use Nginx and Node.js servers. The process involves uploading a file from a browser to Nginx, which then forwards it to Node.js for processing. However, I've encountered an issue when dealing with large files - the upload crashe ...

What is causing the child table (toggle-table) to duplicate every time a row in the parent table is clicked?

After creating a table containing GDP data for country states, I've noticed that when a user clicks on a state row, the child table displaying district GDP appears. However, there seems to be an issue with the child table as it keeps repeating. I&apos ...