|
| 1 | +import { writeFile } from "node:fs/promises"; |
| 2 | +import mongoose from "mongoose"; |
| 3 | + |
| 4 | +const keyFields = ["subject", "exam", "slot", "year"]; |
| 5 | + |
| 6 | +const args = process.argv.slice(2); |
| 7 | +const shouldDelete = args.includes("--delete"); |
| 8 | +let collectionName = "paperrequests"; |
| 9 | + |
| 10 | +for (const [index, arg] of args.entries()) { |
| 11 | + if (arg.startsWith("--collection=")) { |
| 12 | + collectionName = arg.slice("--collection=".length); |
| 13 | + } else if (arg === "--collection") { |
| 14 | + const name = args[index + 1]; |
| 15 | + if (!name || name.startsWith("--")) { |
| 16 | + console.error("--collection needs a name, e.g. --collection paperrequests"); |
| 17 | + process.exit(1); |
| 18 | + } |
| 19 | + collectionName = name; |
| 20 | + } |
| 21 | +} |
| 22 | + |
| 23 | +const mongoUri = process.env.MONGODB_URI; |
| 24 | + |
| 25 | +if (!mongoUri) { |
| 26 | + console.error( |
| 27 | + "set MONGODB_URI, e.g. node --env-file=.env scripts/merge-duplicate-paper-requests.mjs", |
| 28 | + ); |
| 29 | + process.exit(1); |
| 30 | +} |
| 31 | + |
| 32 | +function describe(fields) { |
| 33 | + return keyFields.map((field) => fields[field] ?? "(none)").join(" | "); |
| 34 | +} |
| 35 | + |
| 36 | +async function main() { |
| 37 | + await mongoose.connect(mongoUri); |
| 38 | + const db = mongoose.connection.db; |
| 39 | + |
| 40 | + const existing = (await db.listCollections({}, { nameOnly: true }).toArray()) |
| 41 | + .map((collection) => collection.name) |
| 42 | + .sort(); |
| 43 | + if (!existing.includes(collectionName)) { |
| 44 | + console.error( |
| 45 | + `no collection named ${collectionName}. this database has: ${existing.join(", ") || "nothing"}. pick it with --collection <name>`, |
| 46 | + ); |
| 47 | + process.exitCode = 1; |
| 48 | + return; |
| 49 | + } |
| 50 | + |
| 51 | + const requests = db.collection(collectionName); |
| 52 | + const groups = await requests |
| 53 | + .aggregate([ |
| 54 | + { $sort: { createdAt: 1, _id: 1 } }, |
| 55 | + { |
| 56 | + $group: { |
| 57 | + _id: Object.fromEntries(keyFields.map((field) => [field, `$${field}`])), |
| 58 | + ids: { $push: "$_id" }, |
| 59 | + }, |
| 60 | + }, |
| 61 | + { $match: { "ids.1": { $exists: true } } }, |
| 62 | + ]) |
| 63 | + .toArray(); |
| 64 | + |
| 65 | + const extraIds = groups.flatMap((group) => group.ids.slice(1)); |
| 66 | + |
| 67 | + console.log( |
| 68 | + `${collectionName}: ${groups.length} papers requested more than once, ${extraIds.length} extra rows`, |
| 69 | + ); |
| 70 | + for (const group of groups) { |
| 71 | + console.log( |
| 72 | + ` ${describe(group._id)}: ${group.ids.length} rows, keeping the first, ${String(group.ids[0])}`, |
| 73 | + ); |
| 74 | + } |
| 75 | + |
| 76 | + if (!shouldDelete) { |
| 77 | + console.log( |
| 78 | + "\nnothing was changed. run again with --delete to remove the extra rows and add the unique index", |
| 79 | + ); |
| 80 | + return; |
| 81 | + } |
| 82 | + |
| 83 | + if (extraIds.length) { |
| 84 | + const removed = await requests.find({ _id: { $in: extraIds } }).toArray(); |
| 85 | + const backupFile = `paper-request-duplicates-${new Date().toISOString().replace(/[:.]/g, "-")}.json`; |
| 86 | + await writeFile(backupFile, JSON.stringify(removed, null, 2)); |
| 87 | + console.log(`\nsaved the rows being removed to ${backupFile}`); |
| 88 | + |
| 89 | + const { deletedCount } = await requests.deleteMany({ _id: { $in: extraIds } }); |
| 90 | + console.log(`deleted ${deletedCount} from ${collectionName}`); |
| 91 | + } |
| 92 | + |
| 93 | + const indexName = await requests.createIndex( |
| 94 | + Object.fromEntries(keyFields.map((field) => [field, 1])), |
| 95 | + { unique: true }, |
| 96 | + ); |
| 97 | + console.log(`unique index ${indexName} is in place`); |
| 98 | +} |
| 99 | + |
| 100 | +try { |
| 101 | + await main(); |
| 102 | +} catch (error) { |
| 103 | + console.error(error); |
| 104 | + process.exitCode = 1; |
| 105 | +} finally { |
| 106 | + await mongoose.disconnect(); |
| 107 | +} |
0 commit comments