94 lines
2.6 KiB
JavaScript
94 lines
2.6 KiB
JavaScript
const { MongoClient } = require('mongodb');
|
|
const fs = require('fs');
|
|
const path = require('path');
|
|
|
|
const MONGODB_URI = 'mongodb://localhost/beanstalk';
|
|
const DB_DIR = path.join(__dirname, '../public/db');
|
|
|
|
async function importDatabase() {
|
|
const client = new MongoClient(MONGODB_URI);
|
|
|
|
try {
|
|
console.log('Connecting to MongoDB...');
|
|
await client.connect();
|
|
|
|
const db = client.db();
|
|
|
|
// Check if DB directory exists
|
|
if (!fs.existsSync(DB_DIR)) {
|
|
console.error(`Error: Database directory not found: ${DB_DIR}`);
|
|
process.exit(1);
|
|
}
|
|
|
|
console.log('Reading JSON files...');
|
|
const files = fs.readdirSync(DB_DIR).filter(file => file.endsWith('.json'));
|
|
|
|
if (files.length === 0) {
|
|
console.log('No JSON files found in the database directory.');
|
|
return;
|
|
}
|
|
|
|
for (const file of files) {
|
|
const collectionName = path.basename(file, '.json');
|
|
const filePath = path.join(DB_DIR, file);
|
|
|
|
console.log(`\nImporting collection: ${collectionName}`);
|
|
|
|
try {
|
|
const data = JSON.parse(fs.readFileSync(filePath, 'utf8'));
|
|
|
|
if (!Array.isArray(data)) {
|
|
console.log(` ⚠️ Warning: ${file} does not contain an array. Skipping.`);
|
|
continue;
|
|
}
|
|
|
|
// Drop existing collection
|
|
await db.collection(collectionName).drop().catch(() => {});
|
|
console.log(` ✓ Dropped existing collection`);
|
|
|
|
// Insert data
|
|
if (data.length > 0) {
|
|
const result = await db.collection(collectionName).insertMany(data);
|
|
console.log(` ✓ Inserted ${result.insertedCount} documents`);
|
|
} else {
|
|
console.log(` ✓ Collection is empty`);
|
|
}
|
|
|
|
} catch (error) {
|
|
console.error(` ✗ Error importing ${file}:`, error.message);
|
|
}
|
|
}
|
|
|
|
console.log('\nDatabase import completed successfully!');
|
|
|
|
} catch (error) {
|
|
console.error('Error importing database:', error);
|
|
process.exit(1);
|
|
} finally {
|
|
await client.close();
|
|
}
|
|
}
|
|
|
|
// Handle command line arguments
|
|
const args = process.argv.slice(2);
|
|
if (args.includes('--help') || args.includes('-h')) {
|
|
console.log(`
|
|
Usage: node import-db.js [options]
|
|
|
|
Options:
|
|
--help, -h Show this help message
|
|
|
|
Description:
|
|
Imports JSON files from public/db directory into MongoDB.
|
|
Each JSON file corresponds to a collection with the same name (without .json extension).
|
|
|
|
The script will:
|
|
1. Drop existing collections
|
|
2. Create new collections with the imported data
|
|
3. Preserve all document structure and data
|
|
`);
|
|
process.exit(0);
|
|
}
|
|
|
|
importDatabase();
|