|
| 1 | +const { MongoClient } = require('mongodb'); |
| 2 | + |
| 3 | +const { |
| 4 | + RTCSTATS_MONGODB_URI, |
| 5 | + RTCSTATS_MONGODB_NAME, |
| 6 | + RTCSTATS_METADATA_COLLECTION |
| 7 | +} = process.env; |
| 8 | + |
| 9 | + |
| 10 | +if (!RTCSTATS_MONGODB_URI || !RTCSTATS_MONGODB_NAME || !RTCSTATS_METADATA_COLLECTION) { |
| 11 | + console.error( |
| 12 | + 'Error: RTCSTATS_MONGODB_URI, RTCSTATS_MONGODB_NAME, and RTCSTATS_METADATA_COLLECTION ' |
| 13 | + + 'environment variables must be set.' |
| 14 | + ); |
| 15 | + process.exit(1); |
| 16 | +} |
| 17 | + |
| 18 | +const collectionName = RTCSTATS_METADATA_COLLECTION; |
| 19 | + |
| 20 | +const indexDefinitions = [ |
| 21 | + { |
| 22 | + key: { |
| 23 | + conferenceId: 1, |
| 24 | + dumpId: 1 |
| 25 | + }, |
| 26 | + name: 'PK_conferenceId_dumpId', |
| 27 | + unique: true |
| 28 | + }, |
| 29 | + { |
| 30 | + key: { |
| 31 | + conferenceUrl: 1, |
| 32 | + startDate: 1 |
| 33 | + }, |
| 34 | + name: 'GSI_conferenceUrl_startDate' |
| 35 | + }, |
| 36 | + { |
| 37 | + key: { conferenceId: 1, |
| 38 | + startDate: 1 |
| 39 | + }, |
| 40 | + name: 'GSI_conferenceId_startDate' |
| 41 | + }, |
| 42 | + { |
| 43 | + key: { sessionId: 1, |
| 44 | + startDate: 1 |
| 45 | + }, |
| 46 | + name: 'GSI_sessionId_startDate' |
| 47 | + } |
| 48 | +]; |
| 49 | + |
| 50 | + |
| 51 | +/** |
| 52 | + * Resets the MongoDB collection and applies the required indexes. |
| 53 | + * It drops the collection if it already exists to ensure a clean state. |
| 54 | + * @returns {Promise<void>} |
| 55 | + */ |
| 56 | +async function resetMongoDB() { |
| 57 | + const client = new MongoClient(RTCSTATS_MONGODB_URI); |
| 58 | + |
| 59 | + try { |
| 60 | + await client.connect(); |
| 61 | + console.log('Successfully connected to MongoDB server.'); |
| 62 | + |
| 63 | + const db = client.db(RTCSTATS_MONGODB_NAME); |
| 64 | + const collection = db.collection(collectionName); |
| 65 | + |
| 66 | + const collections = await db.listCollections({ name: collectionName }).toArray(); |
| 67 | + |
| 68 | + if (collections.length > 0) { |
| 69 | + console.log(`Collection '${collectionName}' already exists. Dropping and recreating...`); |
| 70 | + await collection.drop(); |
| 71 | + console.log(`Collection '${collectionName}' dropped successfully.`); |
| 72 | + } |
| 73 | + |
| 74 | + console.log(`Creating new collection '${collectionName}' and applying indexes...`); |
| 75 | + const result = await collection.createIndexes(indexDefinitions); |
| 76 | + |
| 77 | + console.log('Successfully created indexes:', result); |
| 78 | + |
| 79 | + } catch (err) { |
| 80 | + console.error('An error occurred during MongoDB setup:', err); |
| 81 | + } finally { |
| 82 | + await client.close(); |
| 83 | + console.log('MongoDB connection closed.'); |
| 84 | + } |
| 85 | +} |
| 86 | + |
| 87 | +resetMongoDB(); |
0 commit comments