-
Notifications
You must be signed in to change notification settings - Fork 0
/
insertData.js
73 lines (64 loc) · 2.21 KB
/
insertData.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
63
64
65
66
67
68
69
70
71
72
73
const client = require("./db.js");
const csvtojson = require("csvtojson");
const fs = require("fs");
const path = require("path");
async function processCSVFile(filePath) {
try {
// Connects to the server
await client.connect();
// Collection that we are inserting into
// Use Test collection to mess around with new data
const collection = client
.db("Baseball-Database")
.collection("Pitcher-Data");
// Temporary storage of data
const tempData = [];
// Changes CSV -> JSON and pushes it into tempData
await csvtojson()
.fromFile(filePath)
.then((source) => {
for (let i = 0; i < source.length; i++) {
const oneRow = {
player_name: source[i]["player_name"],
Pitcher_Throwing_arm: source[i]["p_throws"],
game_date: source[i]["game_date"],
count: source[i]["balls"] + "-" + source[i]["strikes"],
pitch_name: source[i]["pitch_name"],
pitch_type: source[i]["pitch_type"],
release_speed: source[i]["release_speed"],
release_spin_rate: source[i]["release_spin_rate"],
horizontal_pitch_movement: source[i]["pfx_x"],
vertical_pitch_movement: source[i]["pfx_z"],
description: source[i]["description"],
zone: source[i]["zone"],
plate_location_horizontal: source[i]["plate_x"],
plate_location_vertical: source[i]["plate_z"],
};
tempData.push(oneRow);
}
});
// Pushes data from tempData -> Collection
await collection.insertMany(tempData);
console.log(`Imported CSV ${filePath} into database successfully!`);
} finally {
// Closes connection to DB
await client.close();
}
}
async function run() {
try {
const folderPath = "./pitcher_data"; // Path to the folder containing CSV files
// Read directory
const files = fs.readdirSync(folderPath);
// Process each CSV file
for (const file of files) {
const filePath = path.join(folderPath, file);
if (path.extname(filePath).toLowerCase() === ".csv") {
await processCSVFile(filePath);
}
}
} catch (error) {
console.error("Error:", error);
}
}
run();