-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmongo-csv.js
executable file
·55 lines (48 loc) · 1.57 KB
/
mongo-csv.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
#! /usr/bin/env node
const fs = require('fs');
const { MongoClient } = require('mongodb');
const { parse } = require('json2csv');
const mongoQuery = require('./lib/mongo-query');
const parseMethod = require('./lib/parse-method');
const config =require(`${process.cwd()}/config.json`);
const url = config.url || 'mongodb://localhost:27017';
const databaseName = config.databaseName;
const authDb = config.authDb || config.databaseName;
const collection = config.collection;
const outputFilePath = config.outputFilePath || './query_results.csv';
const query = config.query || {};
const options = config.options || {};
const method = config.method ? parseMethod(config.method) : 'find';
(async function() {
const auth = (process.env.MONGO_USER || config.mongoUser)
? {
auth: {
user: process.env.MONGO_USER || config.mongoUser,
password: process.env.MONGO_PASSWORD || config.mongoPassword,
},
}
: {};
const client = new MongoClient(url, {
useNewUrlParser: true,
authSource: authDb,
...auth,
});
try {
await client.connect();
const db = client.db(databaseName);
const cursor = db.collection(collection)[method](mongoQuery(query), options);
const documents = [];
while (await cursor.hasNext()) {
const document = await cursor.next();
documents.push(document);
}
if (documents.length === 0) {
console.error('0 documents were found, aborting');
process.exit(1);
}
fs.writeFileSync(outputFilePath, parse(documents));
} catch (err) {
console.log(err.stack);
}
client.close();
})();