草庐IT

node.js - NodeJS MongoDB Mongoose 将嵌套的子文档和数组导出到 XLSX 列

coder 2023-11-05 原文

我有来自 MongoDB 的查询结果,作为包含嵌套子文档和子文档数组的文档数组。

[
  {
    RecordID: 9000,
    RecordType: 'Item',
    Location: {
      _id: 5d0699326e310a6fde926a08,
      LocationName: 'Example Location A'
    }
    Items: [
      {
        Title: 'Example Title A',
        Format: {
          _id: 5d0699326e310a6fde926a01,
          FormatName: 'Example Format A'
        }
      },
      {
        Title: 'Example Title B',
        Format: {
          _id: 5d0699326e310a6fde926a01,
          FormatName: 'Example Format B'
        }
      }
    ],
  },
  {
    RecordID: 9001,
    RecordType: 'Item',
    Location: {
      _id: 5d0699326e310a6fde926a08,
      LocationName: 'Example Location C'
    },
    Items: [
      {
        Title: 'Example Title C',
        Format: {
          _id: 5d0699326e310a6fde926a01,
          FormatName: 'Example Format C'
        }
      }
    ],
  }
]

问题

我需要按列顺序将结果导出到 XLSX。 XLSX 库正在努力仅导出顶级 属性(例如 RecordID 和 RecordType)。我还需要导出嵌套对象和对象数组。给定一个属性名称列表,例如RecordID、RecordType、Location.LocationName、Items.Title、Items.Format.FormatName 属性必须按指定顺序导出到 XLSX 列。

想要的结果

这是所需的“扁平化”结构(或类似结构) 我认为应该能够转换为 XLSX 列。

[
  {
    'RecordID': 9000,
    'RecordType': 'Item',
    'Location.LocationName': 'Example Location A',
    'Items.Title': 'Example Title A, Example Title B',
    'Items.Format.FormatName': 'Example Format A, Example Format B',
  },
  {
    'RecordID': 9001,
    'RecordType': 'Item',
    'Location.LocationName': 'Example Location C',
    'Items.Title': 'Example Title C',
    'Items.Format.FormatName': 'Example Format C',
  }
]

我正在使用 XLSX 库将查询结果转换为仅适用于顶级属性的 XLSX。

  const worksheet: XLSX.WorkSheet = XLSX.utils.json_to_sheet(results.data);
  const workbook: XLSX.WorkBook = { Sheets: { 'data': worksheet }, SheetNames: ['data'] };
  const excelBuffer: any = XLSX.write(workbook, { bookType: 'xlsx', type: 'array' });

  const data: Blob = new Blob([excelBuffer], { type: EXCEL_TYPE });
  FileSaver.saveAs(data, new Date().getTime());

可能的选择

我猜我需要在查询中使用聚合或通过在返回查询时执行后处理来“展平”结构。

选项 1:在 MongoDB 查询中构建逻辑以展平结果。

$replaceRoot可能有效,因为它能够“将现有的嵌入式文档提升到顶层”。虽然我不确定这是否能完全解决问题,但我不想就地修改文档,我只需要将结果展平以便导出。

这是我用来生成结果的 MongoDB 查询:

records.find({ '$and': [ { RecordID: { '$gt': 9000 } } ]},
  { skip: 0, limit: 10, projection: { RecordID: 1, RecordType: 1, 'Items.Title': 1, 'Items.Location': 1 }});

选项 2:在 Node 服务器上迭代并展平结果

这可能不是性能最高的选项,但如果我无法在 MongoDB 查询中找到这样做的方法,这可能是最简单的选项。

更新:

我可以使用 MongoDB 聚合 $project 来“扁平化”结果。例如,这个聚合查询通过“重命名”属性有效地“扁平化”了结果。我只需要弄清楚如何在聚合操作中实现查询条件。

db.records.aggregate({
  $project: {
    RecordID: 1,
    RecordType: 1,
    Title: '$Items.Title',
    Format: '$Items.Format'
  }
})

更新 2:

我放弃了 $project 解决方案,因为我需要更改整个 API 以支持聚合。另外,我需要找到填充的解决方案,因为聚合不支持它,相反,它使用 $lookup 这是可能的但很耗时,因为我需要动态编写查询。我将回过头来研究如何通过创建一个函数来递归地迭代对象数组来展平对象。

最佳答案

下面是一个通过函数 flattenObject 转换服务器上的 Mongo 数据的解决方案,该函数递归地展平嵌套对象并返回嵌套路径的“点类型”键。

请注意 下面的代码片段包含一个呈现和可编辑表格以供预览的函数,但是,您想要的重要部分(下载文件)应该在您运行该代码片段并单击“下载”按钮。

const flattenObject = (obj, prefix = '') =>
  Object.keys(obj).reduce((acc, k) => {
    const pre = prefix.length ? prefix + '.' : '';
    if (typeof obj[k] === 'object') Object.assign(acc, flattenObject(obj[k], pre + k));
    else acc[pre + k] = obj[k];
    return acc;
  }, {});

var data = [{
    RecordID: 9000,
    RecordType: "Item",
    Location: {
      _id: "5d0699326e310a6fde926a08",
      LocationName: "Example Location A"
    },
    Items: [{
        Title: "Example Title A",
        Format: {
          _id: "5d0699326e310a6fde926a01",
          FormatName: "Example Format A"
        }
      },
      {
        Title: "Example Title B",
        Format: {
          _id: "5d0699326e310a6fde926a01",
          FormatName: "Example Format B"
        }
      }
    ]
  },
  {
    RecordID: 9001,
    RecordType: "Item",
    Location: {
      _id: "5d0699326e310a6fde926a08",
      LocationName: "Example Location C"
    },
    Items: [{
      Title: "Example Title C",
      Format: {
        _id: "5d0699326e310a6fde926a01",
        FormatName: "Example Format C"
      }
    }]
  }
];

const EXCEL_MIME_TYPE = `application/vnd.ms-excel`;
const flattened = data.map(e => flattenObject(e));
const ws_default_header = XLSX.utils.json_to_sheet(flattened);
const ws_custom_header = XLSX.utils.json_to_sheet(flattened, {
  header: ['Items.Title', 'RecordID', 'RecordType', 'Location.LocationName', 'Items.Format.FormatName']
});
const def_workbook = XLSX.WorkBook = {
  Sheets: {
    'data': ws_default_header
  },
  SheetNames: ['data']
}

const custom_workbook = XLSX.WorkBook = {
  Sheets: {
    'data': ws_custom_header
  },
  SheetNames: ['data']
}

const def_excelBuffer = XLSX.write(def_workbook, {
  bookType: 'xlsx',
  type: 'array'
});

const custom_excelBuffer = XLSX.write(custom_workbook, {
  bookType: 'xlsx',
  type: 'array'
});

const def_blob = new Blob([def_excelBuffer], {
  type: EXCEL_MIME_TYPE
});

const custom_blob = new Blob([custom_excelBuffer], {
  type: EXCEL_MIME_TYPE
});

const def_button = document.getElementById('dl-def')
/* trigger browser to download file */
def_button.onclick = e => {
  e.preventDefault()
  saveAs(def_blob, `${new Date().getTime()}.xlsx`);
}

const custom_button = document.getElementById('dl-cus')
/* trigger browser to download file */
custom_button.onclick = e => {
  e.preventDefault()
  saveAs(custom_blob, `${new Date().getTime()}.xlsx`);
}

/*
  render editable table to preview (for SO convenience)
*/
const html_string_default = XLSX.utils.sheet_to_html(ws_default_header, {
  id: "data-table",
  editable: true
});

const html_string_custom = XLSX.utils.sheet_to_html(ws_custom_header, {
  id: "data-table",
  editable: true
});
document.getElementById("container").innerHTML = html_string_default;
document.getElementById("container-2").innerHTML = html_string_custom;
<script src="https://cdnjs.cloudflare.com/ajax/libs/xlsx/0.14.3/xlsx.full.min.js"></script>

<head>
  <title>Excel file generation from JSON</title>
  <meta charset="utf-8" />
  <style>
    .xport,
    .btn {
      display: inline;
      text-align: center;
    }
    
    a {
      text-decoration: none
    }
    
    #data-table,
    #data-table th,
    #data-table td {
      border: 1px solid black
    }
  </style>
</head>
<script>
  function render(type, fn, dl) {
    var elt = document.getElementById('data-table');
    var wb = XLSX.utils.table_to_book(elt, {
      sheet: "Sheet JS"
    });
    return dl ?
      XLSX.write(wb, {
        bookType: type,
        bookSST: true,
        type: 'array'
      }) :
      XLSX.writeFile(wb, fn || ('SheetJSTableExport.' + (type || 'xlsx')));
  }
</script>
<div>Default Header</div>
<div id="container"></div>
<br/>
<div>Custom Header</div>
<div id="container-2"></div>
<br/>
<table id="xport"></table>
<button type="button" id="dl-def">Download Default Header Config</button>
<button type="button" id="dl-cus">Download Custom Header Config</button>
<script src="https://cdnjs.cloudflare.com/ajax/libs/FileSaver.js/1.3.8/FileSaver.min.js"></script>

关于node.js - NodeJS MongoDB Mongoose 将嵌套的子文档和数组导出到 XLSX 列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57658767/

有关node.js - NodeJS MongoDB Mongoose 将嵌套的子文档和数组导出到 XLSX 列的更多相关文章

  1. ruby-on-rails - Rails 编辑表单不显示嵌套项 - 2

    我得到了一个包含嵌套链接的表单。编辑时链接字段为空的问题。这是我的表格:Editingkategori{:action=>'update',:id=>@konkurrancer.id})do|f|%>'Trackingurl',:style=>'width:500;'%>'Editkonkurrence'%>|我的konkurrencer模型:has_one:link我的链接模型:classLink我的konkurrancer编辑操作:defedit@konkurrancer=Konkurrancer.find(params[:id])@konkurrancer.link_attrib

  2. ruby - 将散列转换为嵌套散列 - 2

    这道题是thisquestion的逆题.给定一个散列,每个键都有一个数组,例如{[:a,:b,:c]=>1,[:a,:b,:d]=>2,[:a,:e]=>3,[:f]=>4,}将其转换为嵌套哈希的最佳方法是什么{:a=>{:b=>{:c=>1,:d=>2},:e=>3,},:f=>4,} 最佳答案 这是一个迭代的解决方案,递归的解决方案留给读者作为练习:defconvert(h={})ret={}h.eachdo|k,v|node=retk[0..-2].each{|x|node[x]||={};node=node[x]}node[

  3. Ruby——嵌套类和子类是一回事吗? - 2

    下面例子中的Nested和Child有什么区别?是否只是同一事物的不同语法?classParentclassNested...endendclassChild 最佳答案 不,它们是不同的。嵌套:Computer之外的“Processor”类只能作为Computer::Processor访问。嵌套为内部类(namespace)提供上下文。对于ruby​​解释器Computer和Computer::Processor只是两个独立的类。classComputerclassProcessor#Tocreateanobjectforthisc

  4. ruby - 模块嵌套代码风格偏好 - 2

    我的假设是moduleAmoduleBendend和moduleA::Bend是一样的。我能够从thisblog找到解决方案,thisSOthread和andthisSOthread.为什么以及什么时候应该更喜欢紧凑语法A::B而不是另一个,因为它显然有一个缺点?我有一种直觉,它可能与性能有关,因为在更多命名空间中查找常量需要更多计算。但是我无法通过对普通类进行基准测试来验证这一点。 最佳答案 这两种写作方法经常被混淆。首先要说的是,据我所知,没有可衡量的性能差异。(在下面的书面示例中不断查找)最明显的区别,可能也是最著名的,是你的

  5. ruby-on-rails - 使用回形针的嵌套形式 - 2

    我有一个名为posts的模型,它有很多附件。附件模型使用回形针。我制作了一个用于创建附件的独立模型,效果很好,这是此处说明的View(https://github.com/thoughtbot/paperclip):@attachment,:html=>{:multipart=>true}do|form|%>posts中的嵌套表单如下所示:prohibitedthispostfrombeingsaved:@attachment,:html=>{:multipart=>true}do|at_form|%>附件记录已创建,但它是空的。文件未上传。同时,帖子已成功创建...有什么想法吗?

  6. ruby-on-rails - Rails 3,嵌套资源,没有路由匹配 [PUT] - 2

    我真的为这个而疯狂。我一直在搜索答案并尝试我找到的所有内容,包括相关问题和stackoverflow上的答案,但仍然无法正常工作。我正在使用嵌套资源,但无法使表单正常工作。我总是遇到错误,例如没有路线匹配[PUT]"/galleries/1/photos"表格在这里:/galleries/1/photos/1/edit路线.rbresources:galleriesdoresources:photosendresources:galleriesresources:photos照片Controller.rbdefnew@gallery=Gallery.find(params[:galle

  7. ruby - 如何根据长度将路径数组转换为嵌套数组或散列 - 2

    我需要根据字符串路径的长度将字符串路径数组转换为符号、哈希和数组的数组给定以下数组:array=["info","services","about/company","about/history/part1","about/history/part2"]我想生成以下输出,对不同级别进行分组,根据级别的结构混合使用符号和对象。产生以下输出:[:info,:services,about:[:company,history:[:part1,:part2]]]#altsyntax[:info,:services,{:about=>[:company,{:history=>[:part1,:pa

  8. ruby - 鸭子输入字符串、符号和数组的优雅方式? - 2

    这是针对我无法破坏的现有公共(public)API,但我确实希望对其进行扩展。目前,该方法采用字符串或符号或任何其他在作为第一个参数传递给send时有意义的内容我想添加发送字符串、符号等列表的功能。我可以只使用is_a吗?数组,但还有其他发送列表的方法,这不是很像ruby​​。我将调用列表中的map,所以第一个倾向是使用respond_to?:map。但是字符串也会响应:map,所以这行不通。 最佳答案 如何将它们全部视为数组?String的行为与仅包含String的Array相同:deffoo(obj,arg)[*arg].eac

  9. ruby-on-rails - 使用 rspec 和 rails 测试嵌套模块 - 2

    这个问题在这里已经有了答案:关闭10年前。PossibleDuplicate:Testingmodulesinrspec目前我正在使用rspec成功测试我的模块,如下所示:require'spec_helper'moduleServicesmoduleAppServicedescribeAppServicedodescribe"authenticate"doit"shouldauthenticatetheuser"dopending"authenticatetheuser"endendendendend我的模块位于应用程序/服务/services.rb应用程序/服务/app_servi

  10. ruby-on-rails - 嵌套模型验证 - 错误不显示 - 2

    关于这个有很多问题,但似乎都没有帮助。是的,我看过thisrailscast.我有一个作者,他有很多书,像这样:作者:classAuthor书:classBook我创建了以下表单以在authors#show中向作者添加一本书:#labelsandbuttons......使用以下authors_controller方法:defshow@author=Author.find(params[:id])@book=@author.books.buildend...以及以下books_controller方法:defcreate@author=Author.find(params[:autho

随机推荐