title: Convert Date to String in nested array in mongodb
body: <p>I have a mongodb collection called cases and inside cases I have an array of cases per company object.</p>
  
  <p>So the structure is:</p>
  
  <p><a href="https://i.stack.imgur.com/6C9qB.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/6C9qB.png" alt="enter image description here"></a></p>
  
  <p>Inside each case I want to use the createddate (which is a string) and endDate (also string) and convert it to a mongodb date. </p>
  
  <p>When I use NoSQLBooster I add the following query:</p>
  
  <pre><code>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" }}}])
  </code></pre>
  
  <p>This will add a date in a new field - created and then closed. This is exactly what I want.</p>
  
  <p>However, in my code (using mongoose) I have the following:</p>
  
  <p><strong>scripts.commponent.ts:</strong> </p>
  
  <pre><code>runThroughCasesAndConvertDates(id) {
      this.scriptsService.getAllCasesToModify({ companyID : id}).subscribe( res =&gt; {
        if (res.length &gt; 0) {
          for (let i = 0; i &lt; 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();
          }
        }
      });
    }
  </code></pre>
  
  <p><strong>scripts.service.ts</strong></p>
  
  <pre><code>updateDates(body) {
      return this.http.post('/db/cases/updateAllDates', body).pipe(
        map(res =&gt; res.json())
      );
    }
  </code></pre>
  
  <p><strong>casesDB.js</strong></p>
  
  <pre><code>    router.post('/updateAllDates', (req, res) =&gt; {
    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)
     });
  });
  </code></pre>
  
  <p>But it does not add anything into the array. Im really confused as to what Im doing wrong. Maybe there is a better way / approach to doing this?</p>
  
  <p>Thank you</p>