-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
82 lines (78 loc) · 2.98 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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
import mongoose from 'mongoose';
import csv from 'csv-parser';
import fs from 'fs';
import {City, County, State} from "./models/stateCountyCity.js";
mongoose.connect('mongodb://localhost/my_database')
.then(() => console.log('MongoDB Connected'))
.catch(err => console.error(err));
async function Main(stateName, countyName, cityName) {
try {
const state = await State.findOneAndUpdate(
{name: stateName},
{$setOnInsert: {name: stateName}},
{upsert: true, new: true}
).then(async (state) => {
try {
const county = await County.findOneAndUpdate(
{name: countyName},
{
$setOnInsert:
[
{name: countyName},
{state: state.id}
]
},
{upsert: true, new: true}
).then(async (county, state) => {
try {
const city = await City.findOneAndUpdate(
{name: cityName},
{
$setOnInsert:
[
{name: cityName},
{county: county.id}
]
},
{upsert: true, new: true}
).then(async (city, county, state) => {
try {
await State.findOneAndUpdate(
{_id: state._id},
{$push: {counties: County.id}},
);
} catch (error) {
console.error(error);
}
try {
await County.findOneAndUpdate(
{_id: county._id, state: State.id},
{$push: {cities: City._id}},
)
} catch (error) {
console.error(error);
}
})(city, county, state)
} catch (error) {
console.error(error);
}
})(county, state)
} catch (error) {
console.error(error);
}
})(state)
} catch (error) {
console.error(error);
}
}
fs.createReadStream('uscities.csv')
.pipe(csv())
.on('data', (row) => {
const stateName = row.state_name;
const countyName = row.county_name;
const cityName = row.city;
Main(stateName, countyName, cityName);
})
.on('end', () => {
console.log('CSV file successfully processed!');
});