From 89edc7ed0428b31cf3364c16d7155e45cad1b544 Mon Sep 17 00:00:00 2001 From: unknown Date: Tue, 17 Dec 2024 03:16:08 +0200 Subject: [PATCH] added migration --- ...emove-documents-with-non-existent-users.js | 21 +++++++++++++++++++ 1 file changed, 21 insertions(+) create mode 100644 migrations/20241216212401-remove-documents-with-non-existent-users.js diff --git a/migrations/20241216212401-remove-documents-with-non-existent-users.js b/migrations/20241216212401-remove-documents-with-non-existent-users.js new file mode 100644 index 00000000..678954df --- /dev/null +++ b/migrations/20241216212401-remove-documents-with-non-existent-users.js @@ -0,0 +1,21 @@ +module.exports = { + async up(db) { + const allUsers = await db + .collection('users') + .find({}, { projection: { _id: 1 } }) + .toArray() + const allUserIds = allUsers.map((user) => user._id.toString()) + const collections = ['attachments', 'courses', 'lessons', 'notes', 'questions', 'quizzes', 'resourcescategories'] + for (const collectionName of collections) { + const authorsFromCollection = await db.collection(collectionName).distinct('author') + const nonExistingUsers = await authorsFromCollection.filter((userId) => !allUserIds.includes(userId.toString())) + + if (nonExistingUsers.length > 0) { + await db.collection(collectionName).deleteMany({ author: { $in: nonExistingUsers } }) + } + console.log(`Removed ${nonExistingUsers.length} non-existing users from collection ${collectionName}`) + } + }, + + async down() {} +}