Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Select an option

  • Save junftnt/540899fdc2c485e53e765d9bcc8534dd to your computer and use it in GitHub Desktop.

Select an option

Save junftnt/540899fdc2c485e53e765d9bcc8534dd to your computer and use it in GitHub Desktop.
Delete outdated files from Rocket.Chat
/**
* MongoDB query to delete outdated files from Rocket.Chat. You can specify the number of DAYS
* before a file is considered outdated. Deleted files are removed from GridFS completely keeping
* only the message in chat. The message is modified to be a link that points to ALT_LINK instead
* of the file and '(deleted)' is appended to the title.
*
* Tested with MongoDB 3.4
*/
const DAYS = 60;
const ALT_LINK = "/terms-of-service";
let count = 0;
/* Find all messages with files attached */
db.rocketchat_message.find(
{
ts: { $lt: new Date(new Date().getTime() - 1000 * 60 * 60 * 24 * DAYS) },
file: { $exists: true },
attachments: {
$elemMatch: { type: "file" }
}
}
).forEach(function(msg) {
count++;
var oldTitle = msg.attachments.find(function(a) {
return a.type === "file";
}).title;
/* Delete file from GridFS */
db.rocketchat_uploads.remove({ _id: msg.file._id }, true);
db.rocketchat_uploads.files.remove({ _id: msg.file._id }, true);
db.rocketchat_uploads.chunks.remove({ files_id: msg.file._id }, true);
/* Update message to reflect deletion */
db.rocketchat_message.updateOne(
{
_id: msg._id,
attachments: {
$elemMatch: { type: "file" }
}
},
{
$set: {
"attachments.$.type": "link",
"attachments.$.title": oldTitle + " (deleted)",
"attachments.$.title_link": ALT_LINK,
"attachments.$.title_link_download": false
},
$unset: {
"file": true,
"attachments.$.image_url": true,
"attachments.$.image_type": true,
"attachments.$.image_size": true
}
}
);
});
print('Successfully deleted ' + count + ' files.');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment