Javascript 使用Node.js将MongoDB导出到CSV,但会丢失一些列
我想使用以下脚本将表从mongodb导出为csv:Javascript 使用Node.js将MongoDB导出到CSV,但会丢失一些列,javascript,node.js,csv,export-to-csv,Javascript,Node.js,Csv,Export To Csv,我想使用以下脚本将表从mongodb导出为csv: const mongodb = require("mongodb").MongoClient; const fastcsv = require("fast-csv"); const fs = require("fs"); let url = "mongodb://...." mongodb.connect( url, { useNewUrlParser: true, useUnifiedTopology: true }, (err
const mongodb = require("mongodb").MongoClient;
const fastcsv = require("fast-csv");
const fs = require("fs");
let url = "mongodb://...."
mongodb.connect(
url,
{ useNewUrlParser: true, useUnifiedTopology: true },
(err, client) => {
if (err) throw err;
client
.db("mydb")
.collection("mycsv")
.find({})
.toArray((err, data) => {
if (err) throw err;
console.log(data);
fastcsv
.write(data, { headers: true })
.on("finish", function() {
console.log("Write to mycsv.csv successfully!");
})
.pipe(fs.createWriteStream("mycsv.csv"));
client.close();
});
}
);
但是我丢失了一些列,我知道丢失的列是具有许多空值的列(该列的前100行值为空)。我认为问题可能是您没有向fast csv提供任何标题信息。它在文件中指出:
> headers: {null|boolean|string[]} = null:
> If true then the headers will be auto detected from the first row.
> If the row is a one-dimensional array then headers is a no-op
> If the row is an object then the keys will be used
您将“headers”设置为true,这可能会导致第一个数据行被解释为headers,这意味着,如果多个列的数据值为“null”,则这些列将被合并,从而丢失数据
但如果没有额外的信息,真的很难说出什么。发布console.log中要检查的前10个数据条目
尝试通过设置排除标题
.write(data, { headers: false })
从文档中:
alwaysWriteHeaders:{boolean}=false:如果始终希望写入头,即使未写入任何行,也将设置为true。
注意:如果未将标题指定为数组,则会引发错误。您可以使用
csvWriter
而不是下面的fastcvs
首先安装这个节点包。
csvWriter
npm i csv writer--save
()
然后在index.js中或在需要函数的位置。编写以下代码
const createCsvWriter = require('csv-writer').createObjectCsvWriter;
client
.db("mydb")
.collection("mycsv")
.find({})
.toArray((err, data) => {
if (err) throw err;
console.log(data); //data must be an array of objects
const csvWriter = createCsvWriter({
path: './std_folder/Hanuman Madhi.csv',
header: [
{id: 'name', title: 'Name'}, //here id means the key of object and title means the header name displayed on the very first row of csv
{id: 'std', title: 'Std'},
{id: 'address', title: 'Address'},
]
});
csvWriter
.writeRecords(data)
.then(()=> console.log('The CSV file was written successfully'));
client.close();
});
您需要在集合中提供密钥的确切名称以避免此问题 然后fast csv将每个键与每个文档中的值进行匹配,并按如下方式显示指定键的每个值 更改指定标题的此行,如下所示
.write(data, { headers: ["_id","name","age","contact"] }) // make sure each value inside array is exactly same as you have inside your mongodb collection
希望这有帮助抱歉,它不起作用。控制台日志不会返回缺少的列,因此我认为问题是在FastCsvc提供文档的数据结构之前,以及哪些列包含
null
值?看看我的解决方案问题出在find collection上请共享从find collection查询中获得的示例json,那会有帮助的