首页 > 解决方案 > TypeError: xxx.flatMap 不是函数

问题描述

我正在尝试将 xml 文件解析为 json,然后将其批量索引到弹性搜索中。这是我的代码:

require('array.prototype.flatmap').shim()
const fs = require('fs');

const { Client } = require('@elastic/elasticsearch')
const client = new Client({
  node: 'http://localhost:9200'
})

const xml2js = require('xml2js');
const parser = new xml2js.Parser();

fs.readFile(__dirname + '/data.xml', (err, data) => {
    parser.parseString(data, (err, result) => {
        const jsonString = JSON.stringify(result);
        var jsonObj = JSON.parse(jsonString);

        run(jsonObj).catch(console.log)
    });
});

async function run (dataset) {
  await client.indices.create({
    index: 'entity'    
  }, { ignore: [400] })
    
   console.log(dataset)

   const body = dataset.flatMap(doc => [{ index: { _index: 'entity' } }, doc])
// code removed for brevity
}

我可以 console.log(dataset) 并查看它的数据。

在此处输入图像描述

但是当我运行时flatMap,它会遇到错误:

TypeError: dataset.flatMap is not a function

但是,如果我像下面这样传递硬编码值dataset,它就可以工作。

const dataset = [{
    id: 1,
    text: 'If I fall, don\'t bring me back.',
    user: 'jon1',
    date: new Date()
  }, {
    id: 2,
    text: 'Winter is coming',
    user: 'ned', 
    text: 'A Lannister always pays his debts.',
    user: 'tyrion',
    date: new Date()
  }, {
    id: 4,
    text: 'I am the blood of the dragon.',
    user: 'daenerys',
    date: new Date()
  }, {
    id: 5, // change this value to a string to see the bulk response with errors
    text: 'A girl is Arya Stark of Winterfell. And I\'m going home.',
    user: 'arya',
    date: new Date()
        }]

这是我的 package.json

{
  "name": "elasticsearch",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "@elastic/elasticsearch": "^7.11.0",
    "array.prototype.flatmap": "^1.2.4",
    "express": "^4.17.1",
    "fs": "0.0.1-security",
    "util": "^0.12.3",
    "xml2js": "^0.4.23"
  },
  "devDependencies": {
    "eslint": "^7.19.0"
  }
}

标签: javascript

解决方案


该变量dataset包含一个对象。你必须打电话flatMapdataset.PFA.Entity

const body = dataset.PFA.Entity.flatMap(doc => [
  { index: { _index: 'entity' } },
  doc,
])

推荐阅读