-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathseeder.js
More file actions
88 lines (71 loc) · 2.1 KB
/
seeder.js
File metadata and controls
88 lines (71 loc) · 2.1 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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
const fs = require('fs');
const mongoose = require('mongoose');
const colors = require('colors');
const dotenv = require('dotenv');
// Load env vars
dotenv.config({ path: './config/config.env' });
// Load models
const Bootcamp = require('./models/Bootcamp');
const Course = require('./models/Course');
const User = require('./models/User');
const Review = require('./models/Review');
// Connect to DB with increased timeout
mongoose.connect(process.env.MONGO_URI, {
serverSelectionTimeoutMS: 30000, // Increase timeout to 30 seconds
});
// 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 data to database
const importData = async () => {
try {
console.log('⚪ Importing bootcamps...'.yellow);
await Bootcamp.create(bootcamps);
console.log('⚪ Importing courses...'.yellow);
await Course.insertManyWithHook(courses);
console.log('⚪ Importing users...'.yellow);
await User.create(users);
console.log('⚪ Importing reviews...'.yellow);
await Review.create(reviews);
console.log('✅ Data imported'.green);
process.exit();
} catch (error) {
console.log(error.message);
}
};
// delete data
const deleteData = async () => {
try {
await Course.deleteMany();
await Bootcamp.deleteMany();
await User.deleteMany();
await Review.deleteMany();
console.log('🛑 Data Destroyed'.red);
process.exit();
} catch (error) {
console.error(error);
process.exit(1);
}
};
const importCommand = '-i' || '--import';
const deleteCommand = '-d' || '--delete';
if (process.argv[2] === importCommand) {
importData();
} else if (process.argv[2] === deleteCommand) {
deleteData();
} else {
console.log(
'Usage: node seeder -i | --import to import data, -d | --delete to delete data'
);
process.exit();
}