javascript - 将 mongodb 中嵌套数组中的日期转换为字符串

标签 javascript mongodb mongodb-query aggregation-framework momentjs

我有一个名为cases的mongodb集合,在cases内部我有每个公司对象的case数组。

所以结构是:

enter image description here

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

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

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

这将在新字段中添加一个日期 - 创建然后关闭。这正是我想要的。

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

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

但它不会向数组添加任何内容。我真的很困惑我做错了什么。也许有更好的方法/方法来做到这一点?

谢谢

最佳答案

您可以$map覆盖cases数组,并且可以将日期字符串字段更改为日期对象字段。

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

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

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

关于javascript - 将 mongodb 中嵌套数组中的日期转换为字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59786483/

相关文章:

javascript - 仅针对 CSS 中父子之间相同类的第一次直接匹配

javascript - 如何在 THREE.js 中正确制作法线贴图?

JavaScript 眨眼动画

mongodb - mongo查询中文档中键的顺序,重要与否?

javascript - 如何在新打开的窗口中调试 JS?

shell - 如何创建类似 javascript mongodb-tutorial 的浏览器 shell

mongodb - 在MongoDB中查找文档,该文档的数组字段是查询数组的子集

linux - 无法连接到服务器 127.0.0.1 shell/mongo.js

MongoDB:如何在聚合上应用多个 $project

MongoDB $project : $filter sub-array