Converting dates to strings within nested arrays in MongoDB

I have a collection named cases in mongodb, where each company object contains an array of cases.

The structure looks like this:

https://i.sstatic.net/6C9qB.png

Within each case, I need to convert the string values of createddate and endDate into mongodb dates.

When using NoSQLBooster, I execute the following query:

db.cases.aggregate([
{ $match: { companyID: 218 }},
{ $unwind: "$cases" },
{ $match: { 'cases.id': '299' }},
{ $addFields: { 'cases.created':  new Date('2010-06-21T00:00:00.000'), 'cases.closed': new Date('2014-08-29T00:00:00.000') }},
{ $group: { _id: "$_id", cases: { $push: "$cases" }}}])

This operation creates new fields - created and closed - with the desired date values.

However, in my mongoose code, specifically in scripts.commponent.ts:

runThroughCasesAndConvertDates(id) {
    this.scriptsService.getAllCasesToModify({ companyID : id}).subscribe( res => {
      if (res.length > 0) {
        for (let i = 0; i < res[0].cases.length; i++) {
          const caseID = res[0].cases[i].id;
          const data = {
            companyID: id,
            caseID: caseID,
            created: moment(res[0].cases[i].createddate, 'DD-MMM-YYYY h:mm a').format('YYYY-MM-DD[T00:00:00.000Z]'),
            closed: ''
          };
          if (res[0].cases[i].endDate !== '') {
             data.closed = moment(res[0].cases[i].endDate, 'DD-MMM-YYYY h:mm a').format('YYYY-MM-DD[T00:00:00.000Z]');
           }
          this.scriptsService.updateDates(data).subscribe();
        }
      }
    });
  }

In scripts.service.ts:

updateDates(body) {
    return this.http.post('/db/cases/updateAllDates', body).pipe(
      map(res => res.json())
    );
  }

In casesDB.js:

    router.post('/updateAllDates', (req, res) => {
  const { body } = req;
Cases.aggregate([
    { $match: { companyID: body.companyID }},
    { $unwind: "$cases" },
    { $match: { 'cases.id': body.caseID }},
    { $addFields: { 'cases.created':  new Date(body.created), 'cases.closed': new Date(body.closed) } },
    { $group: { _id: "$_id" }
  }],
  function (err, data) {
    res.json(data)
   });
});

Despite implementing this, nothing is being added to the array. I'm puzzled about what might be going wrong. Are there any better approaches to tackle this issue?

Thank you

Answer №1

If you need to iterate over the cases array and convert the date string fields to date object fields, you can utilize the $map function.

Cases.aggregate([
  { "$addFields": {
    "cases": {
      "$map": {
        "input": "$cases",
        "in": {
          "$mergeObjects": [
            "$$this",
            {
              "createddate": {
                "$dateFromString": { "dateString": "$$this.createddate" }
              },
              "endDate": {
                "$dateFromString": { "dateString": "$$this.endDate" }
              }
            }
          ]
        }
      }
    }
  }}
])

Update: In case the dates are empty strings

Cases.aggregate([
  { "$addFields": {
    "cases": {
      "$map": {
        "input": "$cases",
        "in": {
          "$mergeObjects": [
            "$$this",
            {
              "createddate": {
                "$cond": [
                  { "$eq": ["$$this.createddate", ""] },
                  null,
                  { "$dateFromString": { "dateString": "$$this.createddate" } }
                ]
              },
              "endDate": {
                "$cond": [
                  { "$eq": ["$$this.endDate", ""] },
                  null,
                  { "$dateFromString": { "dateString": "$$this.endDate" } }
                ]
              }
            }
          ]
        }
      }
    }
  }}
])

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

Change the way a button interacts with a different element

Currently, I am utilizing SlickSlider from http://kenwheeler.github.io/slick/ and attempting to integrate the Next and Prev buttons with other elements (specifically spans within another container). I have attempted the following: $('button.next&apo ...

"Master the art of curl login authentication with this step-by-step guide

Looking to authenticate using curl with PHP or another language For example, visit this site: When the curl site prompts for authentication as shown in the image below, how do I log in to retrieve data? https://i.sstatic.net/LGNgl.png ...

innerHTML not showing up on the page

Trying to implement a dynamic navbar that changes based on whether a user is signed in or not. The authentication part is functioning correctly (verified with console logs); however, there seems to be an issue with updating the HTML using .innerHTML = ... ...

Executing Server-Side JavaScript Functions in PHP MongoDB MapReduce

First and foremost, I want to clarify that the issue I am facing is more related to the PHP Mongo Driver rather than MongoDB itself. The problem arises when attempting to call MapReduce through PHP. Within my Mongo setup, I have created 3 custom functions ...

Leveraging the power of moment to properly display time in relation to the present

Is there a way to format dates like "a few seconds ago", "10 minutes ago", "a day ago" using momentjs in the browser? var date = moment('2017-01-10T13:53:00'); date = moment(date).fromNow(); When I use date, it shows "in 14 minutes" instead of ...

Communicate with Internet Explorer's JavaScript console using VBA within Excel

I'm encountering an issue when trying to send a basic http post request. While it functions perfectly when sent via ajax in the Internet Explorer console, I'm running into difficulties when attempting to do so in VBA. After some investigation, I& ...

Is there a way to overlay a div on a particular line within a p element?

Within this paragraph lies a collection of text encapsulated by a < p > tag. When this content is displayed on the page, it spans across 5 lines. My objective is to creatively style and position a < div > tag in order to highlight a specific li ...

Generating multiple dropdown menus using PHP

I am currently facing an issue with getting a second dropdown box to repeat another "onchange" function. I have 3 dropdown lists that need to be populated from an SQL database using PHP and javascript/ajax. The first list starts with filled options, and th ...

Is a shifting background image possible?

Can anyone shed some light on how the dynamic background image on this website is created? Is it a JavaScript plugin, a simple .gif, or something else entirely? Appreciate any insights! ...

The AJAX call fails to execute when encountering a 400 bad query response

Whenever I submit this request, it should work perfectly. However, if an attempt is made to create a user with an existing username or email, a 400 bad request response is expected along with details of the issue. The strange thing is that when the reques ...

How do load functions/methods execute in a specific order?

$(document).ready(), $(window).load(function(), <body onload="load()">, data-ng-init="init()", $(function(){...}); It is a challenge to determine the sequence in which different "load" functions are executed across various browsers. There are approx ...

How can I efficiently make a GET request to the server using just plain JavaScript?

What is the most efficient method for making a GET request to the server using pure JavaScript? ...

Problems arise when attempting to load a JSON file using the d3 library installed through npm

I recently added d3 through npm. In my package.json file, the dependencies section shows "d3": "^4.11.0". I attempted to load a simple JSON file using the following code: const d3 = require('d3') d3.json('jsonfile.json', (err, data) ...

What advantages come from destructuring in conjunction with require statements?

When utilizing require, is there a performance advantage or disadvantage to importing the entire module versus only importing selected functions? It's my understanding that when using require to import modules (as opposed to using import), compilers ...

What is the best way to combine two JavaScript lists into a single list of pairs?

I have a pair of lists that are the same length. My goal is to utilize AngularJS to generate a repeated UI table. <tr ng-repeat="pair in pairs ..> For example, with lists [1,2,3,4] and [a,b,c,d]: Table: 1 row: 1 a 2 row: 2 b 3 row: 3 c 4 row: ...

Dynamic creation of HTML/Ionic checkbox leads to ng-change not binding properly

Recently, my team and I have been actively engaged in the process of handling an XML file and dynamically constructing a settings page based on the information extracted from it. Allow me to present an illustration of how these elements are dynamically cre ...

Syntax error encountered while parsing JSON data (jQuery version 1.7.2)

My current challenge involves extracting data from a JSON object located on a different page within my website. This particular page is hosted on an ecommerce platform, which limits my access to server side controls and certain elements. I have encountere ...

What is the method for retrieving the information stored in a response header?

I am looking to extract information from an HTTP response header. My approach involves making an HTTP request using the following code snippet. var token = '123456'; var r = new XMLHttpRequest(); r.open('get', '/api/users/@me&apos ...

Discover the hidden content within a div by hovering over it

Here is an example of a div: <div style="width:500px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;"> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Fusce quis pulvinar dui. Nulla ut metus molestie, dignissim metus et, tinc ...

The function .classList.remove() is effective when applied to one element, but fails to work on a different element

I am facing an issue where only one element is getting affected when trying to remove classes from multiple elements if certain email input requirements are met. Can someone help me understand why this is happening? Here is the code snippet: const emailI ...