-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathimportData.js
60 lines (49 loc) · 1.19 KB
/
importData.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
import mongoose from 'mongoose';
import fs from 'fs';
import * as dotenv from 'dotenv';
dotenv.config({});
import { fileURLToPath } from 'url';
import { dirname } from 'path';
const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);
import Course from './../models/coursesModel.js';
// const User = require('./../../models/userModel');
const DB = process.env.DATABASE.replace(
'<password>',
process.env.DATABASE_PASSWORD,
);
mongoose
.connect(DB, {
useNewUrlParser: true,
useUnifiedTopology: true,
})
.then(() => {});
// READ JSON FILE
const courses = JSON.parse(
fs.readFileSync(`${__dirname}/courses.json`, 'utf-8'),
);
//import the data into the database
const importData = async () => {
try {
await Course.create(courses);
console.log('data add!');
} catch (err) {
console.log(err);
}
process.exit();
};
// delete all data form collections
const deleteData = async () => {
try {
await Course.deleteMany();
console.log('data deleted!');
} catch (err) {
console.log(err);
}
process.exit();
};
if (process.argv[2] === '--import') {
importData();
} else if (process.argv[2] === '--delete') {
deleteData();
}