Tips for updating nested data in mongoose with 2 unique identifiers?

Is there anyone out there with experience in making a Node push function work on nested objects beyond just one level? I'm looking to delve deeper into a second id within the DB model.

// Functional code for updating a user at one level with one id
    const update = await Budget.findOneAndUpdate(
        { '_id': `${id}` },
        {
            '$push': {
                [`${sliceLeft}`]: location
               
            }
        }, { _id: true, new: true }
    )
// Non-functional code! How can I target a second id in a nested object two levels deep?
    let updateDeptArr = await Budget.findOneAndUpdate(
          
          { '_id': `${id}` }, //User id
            {

                '$push': {
                    [`${sliceLeft}.$._id`//Second ID ]: location// Data
                }

            }, { _id: true, new: true }
        )

Answer №1

In order to utilize the $ operator, the array field needs to be included in the query document. Therefore, your query should resemble the following:

let updateDeptArr = await Budget.findOneAndUpdate(
  { 
    '_id': `${id}`,
    [`${sliceLeft}._id`]: YOUR_SECOND_ID
  }, 
  {
    '$push': {
       // The nested array field is dayOutcome as mentioned in OP's comment
       [`${sliceLeft}.$.dayOutcome`]: location
    }
  }...

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

When the fullscreen modal is opened, the initial image displayed is not the same as the one that was clicked on

Seeking assistance: I've been struggling with a problem for quite some time now and could really use some help from you guys. My issue involves an 'AngularJS' webapp that retrieves posts from an 'FB page' via 'OpenGraph' ...

Using regex, match any word along with the preserved white space and consider parentheses as a single word

I need help with creating a regex pattern to split a string of words in a specific way. The current pattern I've been using is (?!\(.*)\s(?![^(]*?\)), but it's not giving me the desired outcome. It's close, but not quite the ...

What is the best way to create individual clickable images that open up a modal window for each one?

Currently, I have created a function that is able to map images from an array in Next.js using react-bootstrap. The function is functioning as expected, however, my goal is to add an onClick function to each image so that when clicked, it opens up in a new ...

Bootstrap 4 Card Body Spinner Overlay with Flex Alignment

Seeking to center a spinner both vertically and horizontally within a bootstrap 4 card body. Despite trying my-auto, justify-content-center & align-items-center, it seems like I'm missing something. I've double-checked the display types and ...

jQuery smooth scrolling problem causing a one-second page "blinking" issue

Currently, I have implemented a smooth scrolling effect on my website using the following jQuery code: jQuery('html,body').animate({scrollTop:scrollTarget}, 1000, "swing"); Although the effect works well in general, I have noticed that when mul ...

The Datetimepicker component outputs the date in datetime format rather than a timestamp

Currently, I am utilizing the datetimepicker JavaScript script with specific implemented logic: <script> var today = new Date(); var dd = today.getDate(); var mm = today.getMonth(); var yy = today.getF ...

Froala Editor: Innovative external toolbar that pops up when the button is clicked

In our project, we are implementing the latest version of Froala and aim to configure it so that the toolbar is activated by a separate external button, similar to Gmail where the editor initially does not display a toolbar. I attempted to modify the &apo ...

What is the best way to assign unique IDs to automatically generated buttons in Angular?

Displayed below is a snippet of source code from an IONIC page dedicated to shapes and their information. Each shape on the page has two buttons associated with it: shape-properties-button and material-information-button. Is it possible to assign different ...

What could be causing the strange output from my filtered Object.values() function?

In my Vue3 component, I created a feature to showcase data using chips. The input is an Object with keys as indexes and values containing the element to be displayed. Here is the complete code documentation: <template> <div class="row" ...

What is the best way to set the sidebar height to 100% in Material-UI?

Trying to learn MUI and encountered a problem. I want the sidebar to cover the full height, I tried 100vh but it stops increasing when the table extends. Using 100% only covers the end of the list. Is there another way to solve this, or is it fine becaus ...

What steps should I take to insert a divider in a dropdown menu?

I am attempting to enhance my dropdown menu by incorporating a separator using the following code: <li class='divider'></li> Below is my HTML code with the separator included: <ul class="dropdown-menu dropdown-menu-right" id="ul ...

Incorporated React component from Rails-assets.org into a Rails application

I have been trying to incorporate a react component from rails-assets.org into my Rails application. Currently, I am using the react-rails gem to write react view in my application. Now, I want to use other react components such as react-router, react-sel ...

Tips for transferring a jQuery array to PHP

I am encountering an issue when trying to send a jQuery array to PHP. Initially, I have one form in HTML and upon clicking 'add', I end up with two forms. Afterwards, I input data into the form which is then stored in a jQuery array. However, I a ...

Discovering the presence of a NAN value within a JSON string

Consider the following scenario: I have a function that receives jsonData in JSON format, and I want to validate the variable jsonData to check for NaN. How can I achieve this? function save() { var jsonData = getEnteredValue(); $.ajax({ ...

Developing a vanilla JavaScript web component with distinct HTML and JavaScript files

As I delve into creating vanilla JS web-components, I am exploring methods to keep the template HTML separate from the JS file, ideally in a distinct HTML file. I have examined various implementations of native JS web-component setups found notably here, ...

Check if the input value was chosen by pressing Enter instead of clicking on it

There is an input tag with the following attributes: <input type="text" name="cOperator" class="form-control scale-input operator" placeholder="Enter your ID" autocomplete="off" onkeyup="ajax_showOptions(this,'getEmp',event)" required> ...

Retrieving data without a specified subdocument or with a particular subdocument in addition to other criteria

I'm in a bind! Imagine you have these items stored in a collection: { _id: ObjectId("53678a557e6e9e19dd4ef1c8"), name: "product 1", rules: [ { type: "one_purchase_per_user" } ], stock: 0, unlimited ...

Could someone help me understand this JavaScript code where a function takes an object as a formal parameter?

Within a Vue component's methods, I came across the following code snippet defining a function: methods: { onEditorChange({ editor, html, text }) { console.log('editor change!', editor, html, text) this.content = html ...

We apologize, but Google Pay encountered an unexpected developer error that caused the request to fail. Please try again later

When attempting to make a payment using Google Pay on a real device in the TEST environment, I am encountering the error mentioned in the title. I have followed the guidance provided in the Google docs and tried converting 'gateway' to a string, ...

Sending various array data via AngularJS

Welcome to the HTML page view where users can input data and send it to an API. https://i.sstatic.net/uJTYc.png Within the form, three parameters need to be passed in a single array: day, fromtime, and to-time. How can these three parameters be passed in ...