-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhelper-script-import-data-from-file.js
More file actions
61 lines (51 loc) · 1.79 KB
/
Copy pathhelper-script-import-data-from-file.js
File metadata and controls
61 lines (51 loc) · 1.79 KB
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
const fs = require('fs');
const mongoose = require('mongoose');
const dotenv = require('dotenv');
const City = require('./model/cityModel');
const User = require('./model/userModel');
dotenv.config({ path: './config.env' });
const DB = process.env.DATABASE.replace(
'<PASSWORD>',
process.env.DATABASE_PASSWORD
);
mongoose.connect(DB, {}).then(() => {
console.log(' DB connection established');
});
//READ JSON FILE WITH CITY DATA
//Can use sync as the funciton here as it will be the first thing to be executed in the process cycle, so doesn't have an effect either way if the asynchronous verison of the function is used or not.
//NOTE: Remember the JSON data needs to be converted into javascript objects so that they can be stored in the database. Mongo will automatically convert the javascript objects to BSON objects for storage.
const cityData = JSON.parse(
fs.readFileSync(`${__dirname}/data/citydata.json`, 'utf8')
);
const userData = JSON.parse(
fs.readFileSync(`${__dirname}/data/userdata.json`, 'utf8')
);
//ADD FILE DATA TO THE DATABASE AUTOMATICALLY
const importData = async () => {
try {
await City.create(cityData);
console.log('city data loaded into db successfully.');
await User.create(userData);
console.log('user data loaded into db successfully.');
} catch (err) {
console.log(err);
}
process.exit();
};
//DELETE ALL FILE DATA FROM THE DATABASE AUTOMATICALLY
const deleteData = async () => {
try {
await City.deleteMany();
await User.deleteMany();
console.log('Collection: City, and User deleted successfully.');
} catch (err) {
console.log(err);
}
process.exit();
};
//EXECUTES THE SCRIPT IN THE COMMAND LINE
if (process.argv[2] === '--importData') {
importData();
} else if (process.argv[2] === '--deleteData') {
deleteData();
}