-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathseeder.js
81 lines (71 loc) · 2.5 KB
/
seeder.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
const fs = require("fs");
const mongoose = require("mongoose");
const dotenv = require("dotenv");
require("colors");
//Load env vars *******************************************************
// dotenv.config({path: "./config/config.env"});
dotenv.config();
//Load models *********************************************************
const Bootcamp = require("./models/BootcampModel");
const Course = require("./models/CourseModel");
const User = require("./models/UserModel");
const Review = require("./models/ReviewModel");
//Connect to DB *******************************************************
// const optionDB = {
// useNewUrlParser: true,
// useCreateIndex: true,
// useFindAndModify: false,
// useUnifiedTopology: true
// };
mongoose.connect(process.env.MONGO_URI).then(() => {
console.log(`Connected MongoDB In Seeder...`.green.inverse);
});
//Read JSON files ******************************************************
const bootcamps = JSON.parse(
fs.readFileSync(`${__dirname}/_data/bootcamps.json`, "utf-8")
);
const courses = JSON.parse(
fs.readFileSync(`${__dirname}/_data/courses.json`, "utf-8")
);
const users = JSON.parse(
fs.readFileSync(`${__dirname}/_data/users.json`, "utf-8")
);
const reviews = JSON.parse(
fs.readFileSync(`${__dirname}/_data/reviews.json`, "utf-8")
);
//Import into DB *******************************************************
const importData = async () => {
try {
await Bootcamp.create(bootcamps, { aggregateErrors: true });
await Course.create(courses, { aggregateErrors: true });
await User.create(users, { aggregateErrors: true });
await Review.create(reviews, { aggregateErrors: true });
console.log("Data Imported.....".green.bold);
process.exit();
} catch (errors) {
console.log(errors);
}
};
//Delete Data from DB ****************************************************
const deleteData = async () => {
try {
await Bootcamp.deleteMany();
await Course.deleteMany();
await User.deleteMany();
await Review.deleteMany();
console.log("Data Destroyed.....".red.bold);
process.exit();
} catch (errors) {
console.log(errors);
}
};
//node seeder.js *********************************************************
if (process.argv[2] === "-i") {
importData().then(() => {
console.log(`Data Import Successfully`.green.bold);
});
} else if (process.argv[2] === "-d") {
deleteData().then(() => {
console.log(`Data Remove DONE`.red.bold);
});
}