From 0cf880aa825c96f4d2c395269f9ff2a014caa57b Mon Sep 17 00:00:00 2001 From: Sai Teja Madha <42540377+saiteja-madha@users.noreply.github.com> Date: Sat, 10 Sep 2022 00:46:59 -0700 Subject: [PATCH] messages migration --- scripts/db-v4-to-v5.js | 57 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 57 insertions(+) diff --git a/scripts/db-v4-to-v5.js b/scripts/db-v4-to-v5.js index bba17c7d2..50115e4ff 100644 --- a/scripts/db-v4-to-v5.js +++ b/scripts/db-v4-to-v5.js @@ -47,6 +47,7 @@ async function migration() { await migrateMemberStats(collections); await migrateMembers(collections); await migrateUsers(collections); + await migrateMessages(collections); } const clearAndLog = (message) => { @@ -316,3 +317,59 @@ const migrateUsers = async (collections) => { console.log(ex); } }; + +/** + * Migrate messages collection from v4 to v5 + * @param {mongoose.Collection[]} collections + */ +const migrateMessages = async (collections) => { + process.stdout.write("📦 Migrating 'messages' collection "); + try { + if ( + !collections.find((c) => c.collectionName === "v4-ticket-backup") && + !collections.find((c) => c.collectionName === "reaction-roles") && + collections.find((c) => c.collectionName === "messages") + ) { + const rrolesC = await mongoose.connection.db.createCollection("reaction-roles"); + const ticketsC = await mongoose.connection.db.createCollection("v4-ticket-backup"); + const messagesC = collections.find((c) => c.collectionName === "messages"); + + const rrToUpdate = await messagesC.find({ roles: { $exists: true, $ne: [] } }).toArray(); + const tToUpdate = await messagesC.find({ ticket: { $exists: true } }).toArray(); + + if (rrToUpdate.length > 0 || tToUpdate.length > 0) { + await rrolesC.insertMany( + rrToUpdate.map((doc) => ({ + guild_id: doc.guild_id, + channel_id: doc.channel_id, + message_id: doc.message_id, + roles: doc.roles, + })) + ); + + await ticketsC.insertMany( + tToUpdate.map((doc) => ({ + guild_id: doc.guild_id, + channel_id: doc.channel_id, + message_id: doc.message_id, + ticket: doc.ticket, + })) + ); + + await mongoose.connection.db.dropCollection("messages"); + + clearAndLog( + `📦 Migrating 'messages' collection | Completed - Updated: ${rrToUpdate.length + tToUpdate.length}` + ); + } else { + await mongoose.connection.db.dropCollection("messages"); + clearAndLog("📦 Migrating 'messages' collection | ✅ No updates required"); + } + } else { + clearAndLog("📦 Migrating 'messages' collection | ✅ No updates required"); + } + } catch (ex) { + clearAndLog("📦 Migrating 'messages' collection | ❌ Error occurred"); + console.log(ex); + } +};