Modifying a nested array found in select documents

One of my JSON entries stored in MongoDB looks like this:

{
_id: "fe50fdee-4ea3-4824-94af-f369633c0c7a",
_class: "com.tracking.daoservice.model.TrackingData",
modified: ISODate("2014-09-10T23:38:48.407Z"),
eventtype: "William-Test",
eventdata: {
    QueryDate: "01-APR-2014",
    SearchQuery: {
        keyword: "Java",
        location: "Santa Clara, CA",
        Facet: "skill~java~perl|workAuth~USC",
        SearchAgentId: "4299"
    },
    Viewed: [
        {
            ViewedID: "8992ade400a",
            Dockey: "3323aba3233",
            PID: "32399a",
            actionsTaken: "email|direct message|report seeker",
            viewDate: "01-APR-2014",
            MessageSent: "true",
            Message: [
                {
                    MessageID: "123aca323",
                    Delivered: "True",
                    Opened: "True",
                    ClickThroughRate: "NotBad",
                    MessageDate: "02-APR-2014",
                    Response: [
                        {
                            ResponseId: "a323a9da",
                            ResponseDate: "23-APR-2014"
                        }
                    ]
                }
            ]
        }
    ]
},
eventsource: "API-Dev Test - JMachine",
sourceip: "myIp",
entityid: "TmoneyBunnyWunny",
groupid: "Dice",
datecreated: ISODate("2014-09-10T23:38:48.405Z")
}

To update specific date attributes within these JSON entries, I wrote a script:

db.TRACKING_DATA.find().forEach(function(doc) { 
  db.TRACKING_DATA.update({ 
    "_id": doc._id,
    "eventdata.Viewed.viewDate":doc.eventdata.Viewed[0].viewDate
  }, { 
    "$set": { "eventdata.Viewed.$.Message.0.MessageDate": new Date( doc.eventdata.Viewed[0].Message[0].MessageDate) }
  } 
  ) 
});

The issue arises when some documents do not contain the 'Message' object:

  Message: [
                {
                    MessageID: "123aca323",
                    Delivered: "True",
                    Opened: "True",
                    ClickThroughRate: "NotBad",
                    MessageDate: "02-APR-2014",
                    Response: [
                        {
                            ResponseId: "a323a9da",
                            ResponseDate: "23-APR-2014"
                        }
                    ]
                }
            ]

This results in the error:

TypeError: Cannot read property '0' of undefined

I am looking for a way to handle this situation with a conditional check:

if(Message exists change these entries within it)

I have attempted various solutions but haven't found one that works:

db.TRACKING_DATA.find().forEach(function(doc) { 
  db.TRACKING_DATA.update(
  { 
    "_id": doc._id,
    "eventdata.Viewed.viewDate":doc.eventdata.Viewed[0].viewDate, doc.eventdata.Viewed[0].Message[0]: {$exists}
  }, 
  { 
    "$set": {"eventdata.Viewed.$.Message.0.MessageDate": new Date( doc.eventdata.Viewed[0].Message[0].MessageDate) }
  } 
  )
});

If you have any insights or suggestions, I would greatly appreciate them!

Thanks,

Answer №1

Implementing some critical thinking will be beneficial.

db.TRACKING_DATA.find().forEach(
    function(doc) {
        var Viewed = doc.eventdata.Viewed;
        if (Viewed instanceof Array && Viewed[0]) {
            var Message = Viewed[0].Message;
            if (Message instanceof Array && Message[0]) {

                db.TRACKING_DATA.update({
                    "_id" : doc._id,
                    "eventdata.Viewed.viewDate" : Viewed[0].viewDate
                }, {
                    "$set" : {
                        "eventdata.Viewed.$.Message.0.MessageDate" : new Date(Message[0].MessageDate)
                    }
                });
            }
        }
    });

To convert the field type from String to Date for every MessageDate in Message, modifications are required in the provided code snippet. The current version only deals with the first element, so adjustments must be made accordingly to align with the original requirements.

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

Is there a method in VBA to access elements generated by javascript code?

After spending several hours conducting thorough research on Google (including browsing StackOverflow), I've been trying to find a method that would allow me to target HTML elements generated by JavaScript in VBA. For instance, using ie.Document.getE ...

Error 431 is encountered when submitting an Axios post request

Facing a 431 (Request Header Fields Too Large) error when trying to submit a form in my single-page project through an axios request. I've attempted setting maxContentLength and maxBodyLength to Infinity, as well as adding max-http-header-size in the ...

The issue arises when attempting to format the date in React before passing it as a parameter in the API

Issue with passing date time value as URL parameter to backend Java API via GET method. The API is only receiving part of the date time string, with the rest being cut off. My React code: const handleStartDate = date => { setStartDate(date); ...

Error message: The attempted import failed because ' is not exported from the module

I am facing an issue with resolving my problem. In a file named lama.d.ts, I have declared a class using the following code: export declare class lama { // code here } After that, I tried to import this class in another file within the same folder ...

Issue encountered while attempting to retrieve data from a local json file due to Cross-Origin Resource Sharing

I'm attempting to fetch and display the contents of a JSON file on a webpage, but I'm encountering this error message: Access to XMLHttpRequest at 'file:///C:/Users/bobal/Documents/htmlTry/myData.json' from origin 'null' has ...

Creating a TeeChart for HTML5 that combines both stacked and normal series can be done by following these steps

Hey there! I'm currently utilizing TeeChart for HTML5 and I'm wondering how to create a chart with both stacked and normal series. Specifically, I need two series to be stacked and a third one to remain unstacked (normal). I attempted to utilize ...

Tailoring information to fit selected preferences

Currently working on developing a fitness app with Vue, aiming to create personalized workout routines based on user preferences. Users can choose specific options and generate a workout plan by clicking a button. The collected data is stored as an object ...

Split a lengthy inventory into separate pages using EJS in combination with jQuery and AJAX

Currently, I am developing a dashboard using Node.js and express. At times, the lists I generate are excessively long, and I need to split them into pages with 20 items each. Users should be able to navigate between pages using buttons. However, I am unsur ...

Use JavaScript to overlay drawings onto an existing image

Within this particular image, I possess a compilation of pixel coordinates outlining the polygon segments that encompass all the objects contained within it (refer to the image provided below). For example, in relation to the individual, there exists a li ...

Steps for sending a value to an AngularJS $http success function

I have a question that is very much like the one posed here: How to pass a value to an AngularJS $http success callback As per Angular.js The $http legacy promise methods success and error have been deprecated. You should use the standard then method ...

Ways to disable an element

How can I prevent a <form:input type="text" path="lateTimeValue" disabled="true" id="lateTime" /> element from sending its value to the server when disabled? What steps should I take to ensure the value is not passed to the server upon submissio ...

What is the best way to access the contents within this specific div element?

Is there a way to extract only the word "square" from within this div's content? <div class="item"> Blue <span>•</span> Square <span>•</span> Infinite </div> I attempted to use innerText.split(), bu ...

What is the most effective method for implementing a fallback image in NextJS?

Lately, I've been immersed in a NextJS project that involves utilizing the YoutubeAPI to retrieve video details, such as thumbnail URLs. When it comes to fetching a full resolution image, the thumbnail URL typically follows this format: https://i.yti ...

Tips for using Cypress to confirm that an HTML element's height or width exceeds a specific value

This thread on Github demonstrates the method for using Cypress to verify that an element has a specific height. cy.get(mainMenu).should('have.css', 'height', '55px') How can I utilize Cypress to confirm that an element exce ...

What is the best way to emphasize case-insensitive searchtext matches in JavaScript?

If I have data containing words like Krishna, krishna, KRISHNA and I enter the search text as 'krish', it will retrieve all three words. However, when I want to highlight the matching result, only the exact matching part of the string is highligh ...

Storing retrieved data in React without using Redux involves using either the Context API or

When using Redux, I have a common store where fetched data is stored. For example, if I navigate away from my videos page (/videos) and then return to it, the videos are still available in the videos reducer. This allows me to show the user already loaded ...

Encountering a problem while attempting to incorporate SQLite into a Node.js environment

I've encountered issues while attempting to import SQLite into node. Here is my import statement: import * as sqlite from './sqlite'; But unfortunately, I am receiving the following error message: node:internal/process/esm_loader:74 int ...

Tips for accessing raw POST data in PHP using $_SERVER

I am facing a challenge with my dynamic page where I use on-page filters that modify the data through AJAX response. My concern is how to access raw POST data when it's not visible in the URL... The link on my page appears as "example.com/default/lis ...

Adjust the width and height of an Angular 5 iframe to match the dimensions of its content

I have multiple iframes and I am looking to dynamically adjust the height and width of each iframe based on its content. For instance, if the content within an iframe is sized at 1300x300, I want the iframe itself to also be 1300x300 when displayed on my ...

Utilizing a Dependency Injection container effectively

I am venturing into the world of creating a Node.js backend for the first time after previously working with ASP.NET Core. I am interested in utilizing a DI Container and incorporating controllers into my project. In ASP.NET Core, a new instance of the c ...