-
-
Save AmShaegar13/8a2be6895e6058e67d05a7596dd9bfca to your computer and use it in GitHub Desktop.
/** | |
* 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.'); |
@PeGaSuS-Coder If you are running via snaps, you can connect to MongoDB using rocketchat-server.mongo
You will also have to run the commands
db.runCommand({compact:"rocketchat_uploads.chunks", force: true})
db.runCommand({compact:"rocketchat_uploads.files", force: true})
db.runCommand({compact:"rocketchat_uploads", force: true})
for reclaiming the space
/> rocketchat-server.mongo
MongoDB shell version v5.0.15
connecting to: mongodb://127.0.0.1:27017/?compressors=disabled&gssapiServiceName=mongodb
Implicit session: session { "id" : UUID("39bc2002-843a-4832-b5a1-8e24dff345b4") }
MongoDB server version: 5.0.15
rs0:PRIMARY> load( "purge_outdated_rocketchat_uploads.js" );
Error: error loading js file: purge_outdated_rocketchat_uploads.js :
@(shell):1:1
what's the issue ?
Hello!
How do i add this to my Rocket.Chat instance?