-
Notifications
You must be signed in to change notification settings - Fork 5
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
eba059c
commit 89edc7e
Showing
1 changed file
with
21 additions
and
0 deletions.
There are no files selected for viewing
21 changes: 21 additions & 0 deletions
21
migrations/20241216212401-remove-documents-with-non-existent-users.js
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -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() {} | ||
} |