-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
62 lines (50 loc) · 1.64 KB
/
index.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
56
57
58
59
60
61
62
const { MongoClient } = require("mongodb");
const fs = require("fs");
const path = require("path");
const { DB_NAME, DOCUMENTS_LIMIT } = require("./config");
/* database url and port, if authentication is required, use the following connection format: mongodb://username:password@url:port */
const client = new MongoClient(`mongodb://localhost:27017/${DB_NAME}`);
const process = async (client) => {
console.time("process");
await client.connect();
const collections = await getAllCollections(client);
const documents = await getAllDocuments(client, collections);
validateAndSave(documents);
client.close();
console.timeEnd("process");
};
const getAllCollections = (client) =>
new Promise((resolve, reject) => {
client
.db()
.listCollections()
.toArray()
.then((colls) => resolve(colls))
.catch((err) => reject(err));
});
const getAllDocuments = async (client, collections) => {
return await Promise.all(
collections.map((coll) => {
const currentCollection = client.db().collection(coll.name);
return currentCollection.find().limit(DOCUMENTS_LIMIT).toArray();
})
);
};
const validateAndSave = (documents) => {
documents.forEach((document) => {
if (document.length > 0) {
document.forEach((doc) => {
const file = path.resolve(__dirname, "./documents.json");
const data = JSON.stringify(doc) + ",\n";
fs.appendFile(file, data, (err) => {
if (err) {
console.log("Log:" + err.message);
} else {
console.log(`Document ${doc._id} saved successfully`);
}
});
});
}
});
};
process(client);