Leveraging an Array of Objects in JavaScript

Need help with my JavaScript code! I want to adjust the date in a Date object by adding specific days and then save it. Here is what I have so far:

let orderIdDateCorrectionDict = [ 
    { "orderId": "2020053100", "dayCorrection": -146 }, 
    { "orderId": "2020053109", "dayCorrection": -146 },
    { "orderId": "2020053100", "dayCorrection": -146 },
];

migrateUp(db.Orders);
var index = 0;

function migrateUp(targetCollection) {

    targetCollection.find({
        OrderId: { $in: orderIdDateCorrectionDict.map(i => i.orderId) }
    }).forEach(
        function (order) {

            order.TransDate.DateTime = order.TransDate.DateTime.addDays(orderIdDateCorrectionDict[index++].dayCorrection);
            order.TransDate.Ticks = NumberLong((order.TransDate.DateTime.getTime() * 10000) + 621355968000000000);

            targetCollection.save(order);
        }
    );
};

Date.prototype.addDays = function (days) {
    var date = new Date(this.valueOf());
    date.setDate(date.getDate() + days);
    return date;
}

I'm encountering this error:

{ "message" : "Cannot read property 'dayCorrection' of undefined", "stack" : "script:9478:126" + "script:14:70" + "script:14:70" + "script:9475:8" + "script:9460:1" }

What adjustments should I make to update the records correctly with the day integer value?

Answer №1

The issue indicates that there may be duplicate order IDs within the dataset. This causes the find function to return more orders than there are entries in orderIdDateCorrectionDict, leading to the index going beyond the array's end and resulting in an undefined value ("cannot read property ... of undefined").

To troubleshoot, ensure that querying N number of IDs returns exactly N orders. Any deviation suggests non-unique IDs, requiring a fix where these duplicates originate.

To prevent this problem in the OP code regardless of how the IDs are structured, avoid using a parallel index counter. Instead, retrieve the correction by orderId like so:

function orderCorrectionForId(orderId) {
  return orderIdDateCorrectionDict.find(oc => oc.orderId === orderId)
}

// Eliminate the need for the index variable
// inside the forEach loop...

function (order) {
  let correction = orderCorrectionForId(order.OrderId)
  if (correction) {
    order.TransDate.DateTime = order.TransDate.DateTime.addDays(correction.dayCorrection);
    // continue as necessary...
  }

Initially, start by logging the order in the forEach function to pinpoint the root issue – unexpected query results.

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

Issues with the Textarea StartsWith Function Being Unresponsive

Attempting to use the startsWith function on a textarea, but it seems like there may be an error in my code. Since I am not well-versed in Javascript, please forgive any obvious mistakes. I did try to implement what made sense to me... View the Fiddle here ...

Accessing/Storing Pictures in MongoDB using Mongoose

I've been struggling with managing images in MongoDB for a while now. Everywhere I look suggests using GridFS because of the 16mb size limit per document. However, the documents I want to store are all <16mb each. Currently, I am storing it like th ...

What is the best way to obtain the output of the MULTIPLO.SUPERIOR function using JavaScript?

In Microsoft Excel, there is a function called upper multiple where we can input a number and it will round up to the nearest multiple of a second specified number - for example: 10,986 ; 5 = 15 105,32 ; 5 = 110 ...

Pagination activates on the second tap

Check out my example on jsFiddle: https://jsfiddle.net/0se06am5/ class Pagination extends React.Component { constructor(props) { super(props); this.state = { current: 1 }; this.items = ['a', 'b', 'c&ap ...

Unique validation feature implemented in Parsley.js runs through validation loop twice

I've spent the entire afternoon trying to figure this out, but I just can't seem to debug it. The issue arises when I do a hard refresh of the page and my custom async validator runs twice, yet only sends one request to the server. window.Parsle ...

The component <FormControl /> does not support the variant prop

It's perplexing to me why <FormControl /> doesn't seem to accept the prop variant. Even though the documentation suggests that this prop is available. import React from "react"; import { render } from "react-dom"; import FormControl from " ...

Transforming conversion code snippet from jQuery to Dojo - utilizing AJAX techniques

I am in the process of converting my code from jQuery to Dojo. I just need an equivalent snippet that works. The jQuery code is functioning properly, but the Dojo code is not working as expected. JQUERY <script type="text/javascript"> $(docume ...

Sorting a collection of objects into separate arrays

When working with React, here is an example of the state configuration I am using: state = { Producers: [], France: [], Spain: [], Germany: [], Portugal: [], Greece: [], Austria: [], isLoading: false }; I ...

Create an Oval-Shaped Image Cutout

Currently, I have a fabric.JS canvas where objects can be added. However, I am interested in clipping these objects into an oval shape, similar to the clip demos on fabricjs.com. In my current project (JSFiddle), I have been able to crop the object into a ...

React- The Autocomplete/Textfield component is not displaying properly because it has exceeded the maximum update depth limit

My autocomplete field is not displaying on the page even though I wrapped it with react-hook-form for form control. When I check the console, I see this error: index.js:1 Warning: Maximum update depth exceeded. This can happen when a component calls setSt ...

What is the best way to assign the result of a promise to a variable?

My code includes an async function that retrieves a value async fetchUserName(environment: string, itemName: string, authToken: string): Promise<any> { let result = await this.obtainDeviceName(environment, itemName, authToken); return ...

Is it possible to use jQuery/JS to automatically format currency input as it is typed, adding a 1000 separator and ensuring

I'm working on a text input field that needs to format the value as it is being typed, with restrictions of 2 decimal places and 1000 separators. This field should only allow for digits to be entered. Specifically, this input is meant for users to ent ...

I am attempting to display films within a watchlist module, however it is not allowing me to do so

I have developed a small movie database and need to showcase movies on my watchlist. While I am able to search for movies, adding them to my watchlist is only reflected in the Homescreen component and not in the WatchList component. This is the current s ...

Is it possible to integrate Wavify with React for a seamless user experience?

For my website designs, I have been experimenting with a JavaScript library known as Wavify (https://github.com/peacepostman/wavify) to incorporate wave animations. Recently delving into the world of React, I pondered whether I could integrate Wavify into ...

jQuery - accessing a different class within the object

Let me explain the scenario: I have a website that will delve into 4 different subjects. Initially, I have 4 divs each representing the title of those subjects. For instance, <div><p> Physics </p></div> <div><p> Chem ...

Can a Vue component in SFC form be utilized as a mixin?

Consider this scenario, where I have a component created in SFC format: // Parent.vue <template> <div> {{ txt }} </div> </template> <script> export default { name: 'ParentComponent', data() { return ...

Rendering issues arise in the app when utilizing browserHistory instead of hashHistory with React Router

I have integrated React Router into my current project in the following way: const store = Redux.createStore(bomlerApp); const App = React.createClass({ render() { return ( React.createElement('div', null, ...

Hide the scroll bar in html/css while keeping the functionality of the arrows intact

Is there a way to remove the scroll bar but still be able to access overflown data using arrows? Any assistance would be greatly appreciated. Thank you in advance. ...

What is the best way to ensure the alignment of list content and numbering remains separate in HTML while using list-style-position set to inside?

Below is a list with customized styling: ol { background: #ff9999; padding: 20px; list-style-position: inside; } ol li { background: #ffe5e5; padding: 5px; } <ol> <li>Coffee</li> <li>Tea</li> <li>Coca ...

Why are the elements not found by their id when I check them, even though they were created dynamically using an ajax-generated form with php-inserted values through a

How can I prepopulate form fields displayed in a modal view using jQuery after retrieving the form HTML with an AJAX query? I am trying to set the values through a JavaScript function that retrieves PHP-generated values via document.getElementById. However ...