From 1928f0e39fa1605943b019d00f3c007b4c57d58e Mon Sep 17 00:00:00 2001 From: Nicolas Burtey Date: Wed, 20 Dec 2023 17:19:53 -0600 Subject: [PATCH] chore: adding 1st migration script --- .../20231220170640-quiz-new-collection-1.ts | 39 +++++++++++++++++++ 1 file changed, 39 insertions(+) create mode 100644 core/api/src/migrations/20231220170640-quiz-new-collection-1.ts diff --git a/core/api/src/migrations/20231220170640-quiz-new-collection-1.ts b/core/api/src/migrations/20231220170640-quiz-new-collection-1.ts new file mode 100644 index 00000000000..98c801d2061 --- /dev/null +++ b/core/api/src/migrations/20231220170640-quiz-new-collection-1.ts @@ -0,0 +1,39 @@ +/* eslint @typescript-eslint/ban-ts-comment: "off" */ +// @ts-nocheck +async function migrateAccounts(db, batchSize = 100) { + const cursor = db.collection("accounts").find() + + let batchCount = 0 + while (await cursor.hasNext()) { + const quizUpdates = [] + for (let i = 0; i < batchSize && (await cursor.hasNext()); i++) { + const account = await cursor.next() + for (const quizId of account.earn) { + quizUpdates.push({ + create: { + accountId: account._id, + quizId, + createAt: new Date(), + }, + }) + } + } + + batchCount += quizUpdates.length + + if (quizUpdates.length > 0) { + await db.collection("quizs").bulkWrite(quizUpdates) + console.log(`Processed ${batchCount} accounts`) + } + } + + console.log(`Processed ${batchCount} accounts`) +} + +module.exports = { + async up(db) { + console.log("Begin migration to Quiz collection") + await migrateAccounts(db) + console.log("Migration completed") + }, +}