-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdeletedb.js
More file actions
67 lines (58 loc) · 2.33 KB
/
Copy pathdeletedb.js
File metadata and controls
67 lines (58 loc) · 2.33 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
const dotenv = require('dotenv');
const readline = require('readline');
dotenv.config();
const connectToDB = require('./db/db'); // Adjust the path to your db connection file
const mongoose = require('mongoose');
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
const waitForConnection = () => {
return new Promise((resolve, reject) => {
const interval = setInterval(() => {
if (mongoose.connection.readyState === 1) {
clearInterval(interval);
resolve();
} else if (mongoose.connection.readyState === 0) {
clearInterval(interval);
reject(new Error('Connection failed'));
}
}, 500); // Check every 500ms
});
};
const deleteAllCollections = async () => {
try {
// Wait for the database connection to be fully established
await waitForConnection();
// Get the list of all collections in the database
const collections = await mongoose.connection.db.listCollections().toArray();
if (collections.length === 0) {
console.log('No collections found in the database.');
return;
}
console.log('The following collections will be deleted:');
collections.forEach(collection => console.log(`- ${collection.name}`));
rl.question('Are you sure you want to delete all collections? (y/n): ', async (answer) => {
if (answer.toLowerCase() === 'y') {
// Iterate over all collections and drop them
for (const collection of collections) {
await mongoose.connection.db.dropCollection(collection.name);
console.log(`Collection ${collection.name} has been deleted.`);
}
console.log('All collections have been deleted.');
} else {
console.log('Operation canceled. No collections were deleted.');
}
rl.close(); // Close the readline interface only after the user has made a choice
});
} catch (error) {
console.error('Error deleting collections:', error);
rl.close(); // Close readline if there's an error
}
};
if (require.main === module) {
(async () => {
await connectToDB();
await deleteAllCollections();
})();
}