-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathloadJsonToDatabase.js
57 lines (53 loc) · 1.43 KB
/
loadJsonToDatabase.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
const fs = require('fs');
const mongoose = require('mongoose');
const dotenv = require('dotenv');
dotenv.config({ path: './config.env' });
const tours = require('./models/tourmodel');
const users = require('./models/usermodel');
const reviews = require('./models/reviewmodel');
const db = process.env.DATABASE.replace(
'<PASSWORD>',
process.env.DATABASE_PASSWORD
);
mongoose
.connect(db, {
useNewUrlParser: true,
useCreateIndex: true,
useFindAndModify: false,
useUnifiedTopology: true,
})
.then((con) => console.log('Database is connected...'));
const importData = async function (model, data) {
try {
await model.create(data, { validateBeforeSave: false });
console.log('Uploaded');
} catch (err) {
console.log('error ariya hai validation ka');
} finally {
process.exit();
}
};
const deleteData = async function (model) {
try {
await model.deleteMany();
console.log('Deleted');
} catch (err) {
console.log('error ariya hai validation ka');
} finally {
process.exit();
}
};
const toursData = JSON.parse(
fs.readFileSync('./dev-data/data/tours.json', 'utf-8')
);
const usersData = JSON.parse(
fs.readFileSync('./dev-data/data/users.json', 'utf-8')
);
const reviewsData = JSON.parse(
fs.readFileSync('./dev-data/data/reviews.json', 'utf-8')
);
if (process.argv[2] === '--import') {
importData(users, usersData);
} else if (process.argv[2] === '--delete') {
deleteData(users);
}