-
Notifications
You must be signed in to change notification settings - Fork 0
/
seeder.js
84 lines (72 loc) · 1.89 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
82
83
84
const fs = require("fs");
const mongoose = require("mongoose");
const color = require("colors");
const dotenv = require("dotenv");
// Load env vars
dotenv.config({ path: "./src/config/config.env" });
// Load models
const Sentence = require("./src/models/Sentence");
const Vote = require("./src/models/Vote");
const User = require("./src/models/User");
// Connect to DB
mongoose.connect(process.env.MONGO_URI, {
useNewUrlParser: true,
useCreateIndex: true,
useFindAndModify: false,
useUnifiedTopology: true
});
// Read JSON files
const sentences = JSON.parse(
fs.readFileSync(`${__dirname}/src/data/sentences.json`, "utf-8")
);
const votes = JSON.parse(
fs.readFileSync(`${__dirname}/src/data/votes.json`, "utf-8")
);
const users = JSON.parse(
fs.readFileSync(`${__dirname}/src/data/users.json`, "utf-8")
);
// Import into DB
const importData = async () => {
try {
await Sentence.create(sentences);
await Vote.create(votes);
await User.create(users);
console.log("Data Imported...".green.inverse);
process.exit();
} catch (err) {
console.error(err);
}
};
// Delete data
const deleteData = async () => {
try {
await Sentence.deleteMany();
await Vote.deleteMany();
await User.deleteMany();
console.log("Data Destroyed...".red.inverse);
process.exit();
} catch (err) {
console.error(err);
}
};
// Clean votes for approved sentences
const cleanVotes = async () => {
try {
const approvedSentences = await Sentence.find({ isApproved: true });
const approvedSentencesIds = approvedSentences.map(
sentence => sentence._id
);
await Promise.all(
approvedSentencesIds.map(id => Vote.deleteMany({ sentence: id }))
);
} catch (err) {
console.error(err);
}
};
if (process.argv[2] === "-i") {
importData();
} else if (process.argv[2] === "-d") {
deleteData();
} else if (process.argv[2] === "-c") {
cleanVotes();
}