Skip to content

Instantly share code, notes, and snippets.

@travist
Created February 9, 2023 21:19
Show Gist options
  • Save travist/7bd04ca8e9bafd4ce8bbf66b71e5290a to your computer and use it in GitHub Desktop.
Save travist/7bd04ca8e9bafd4ce8bbf66b71e5290a to your computer and use it in GitHub Desktop.
Cleanup a Form.io database with many projects.
/**
* Cleanup the database. This script does the following.
*
* Run this using
* node cleanupdb.js --NODE_CONFIG='{"src": "mongodb://localhost:27017/formio"}'
*/
const config = require('config');
const mongodb = require('mongodb');
const MongoClient = mongodb.MongoClient;
// Query for the projects to delete.
const expiration = Date.now() - (60 * 24 * 60 * 60 * 1000);
const query = {
plan: 'trial',
created: {$lt: new Date(expiration)}
};
(async () => {
const client = new MongoClient(config.src);
await client.connect();
const db = await client.db();
// Delete multiple records in a collection.
async function deleteRecords(name, query, cb) {
const collection = db.collection(name);
if (cb) {
const cursor = collection.find(query);
while (await cursor.hasNext()) {
const record = await cursor.next();
console.groupCollapsed(`Deleting ${name.substr(0, name.length - 1)}: ${record._id.toString()}`);
if (await cb(record)) {
await collection.deleteOne({_id: record._id});
console.log('Delete complete');
}
else {
console.log('Delete has been skipped.');
}
console.groupEnd();
}
}
else {
console.log(`Deleting ${name}`);
await collection.deleteMany(query);
}
}
// Delete things inside of a project.
async function deleteInProject(project) {
await deleteRecords('forms', {project: project._id}, async (form) => {
await deleteRecords('actions', {form: form._id});
await deleteRecords('actionitems', {form: form._id});
await deleteRecords('submissions', {form: form._id});
return true;
});
await deleteRecords('roles', {project: project._id});
await deleteRecords('tags', {project: project._id});
await deleteRecords('formrevisions', {project: project._id});
return true;
}
// Perform the deletion.
await deleteRecords('projects', query, async (project) => await deleteInProject(project));
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment