在MongoDB的嵌套数组中将日期转换为字符串 [英] Convert Date to String in nested array in mongodb

查看:620
本文介绍了在MongoDB的嵌套数组中将日期转换为字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个名为case的mongodb集合,在内部案例中,每个公司对象都有一系列案例.

I have a mongodb collection called cases and inside cases I have an array of cases per company object.

所以结构是:

在每种情况下,我想使用createddate(它是一个字符串)和endDate(也是字符串)并将其转换为mongodb日期.

Inside each case I want to use the createddate (which is a string) and endDate (also string) and convert it to a mongodb date.

当我使用NoSQLBooster时,添加以下查询:

When I use NoSQLBooster I add 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 will add a date in a new field - created and then closed. This is exactly what I want.

但是,在我的代码(使用猫鼬)中,我有以下内容:

However, in my code (using mongoose) I have the following:

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();
        }
      }
    });
  }

scripts.service.ts

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

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)
   });
});

但是它不会在数组中添加任何内容.我真的对我做错了什么感到困惑.也许有更好的方法/方法可以做到这一点?

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?

谢谢

推荐答案

您可以

You can $map over the cases array and can change the date string fields to date object fields.

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

更新:如果日期为空字符串

Update: If dates are blank string

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" } }
                ]
              }
            }
          ]
        }
      }
    }
  }}
])

这篇关于在MongoDB的嵌套数组中将日期转换为字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆