-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathupdateClassDate.js
More file actions
94 lines (79 loc) · 2.8 KB
/
Copy pathupdateClassDate.js
File metadata and controls
94 lines (79 loc) · 2.8 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
89
90
91
92
93
94
//! Run 'npm run refresh' to execute this script and refresh the class dates
// Script to randomize instructor class dates for demo purposes
const { MongoClient } = require("mongodb");
require("dotenv").config();
const uri = `mongodb+srv://${process.env.DB_USER}:${process.env.DB_PASS}@cluster0.y70m6ei.mongodb.net/?retryWrites=true&w=majority`;
const client = new MongoClient(uri);
function randomStartDate() {
// Range: 40 days in the past to 30 days in the future
const pastRange = 40;
const futureRange = 30;
const now = Date.now();
const start = now - pastRange * 24 * 60 * 60 * 1000;
const end = now + futureRange * 24 * 60 * 60 * 1000;
return new Date(start + Math.random() * (end - start));
}
function randomEndDate(startDate) {
const min = 3,
max = 30;
const offset = Math.floor(Math.random() * (max - min + 1)) + min;
const result = new Date(startDate);
result.setDate(result.getDate() + offset);
return result;
}
async function refreshCourses() {
await client.connect();
const db = client.db("PMBIA");
const users = db.collection("users");
const bookings = db.collection("bookings");
const instructors = await users
.find({ role: "Instructor" }, { projection: { classes: 1, name: 1 } })
.toArray();
if (!instructors.length) {
console.error("No instructors found.");
await client.close();
return;
}
for (const instructor of instructors) {
const originalClasses = instructor?.classes || [];
const updatedClasses = [];
for (let i = 0; i < originalClasses.length; i++) {
const cls = originalClasses[i];
const startDate = randomStartDate();
const endDate = randomEndDate(startDate);
updatedClasses.push({ ...cls, startDate, endDate });
await bookings.updateMany(
{
instructorId: instructor._id,
classIndex: i,
},
{
$set: {
startDate,
endDate,
},
}
);
}
await users.updateOne(
{ _id: instructor._id },
{
$set: {
classes: updatedClasses,
"meta.lastUpdated": new Date(),
},
}
);
console.log(`✅ Updated classes for instructor: ${instructor.name}`);
}
console.log("🎉 All instructor classes updated!");
await client.close();
}
module.exports = { refreshCourses };
// If run directly, execute refreshCourses
if (require.main === module) {
refreshCourses().catch((err) => {
console.error("Error updating instructor classes:", err);
client.close();
});
}