Skip to content
Snippets Groups Projects
Commit b814678f authored by Rokas Stankunas's avatar Rokas Stankunas
Browse files

refactored function into connectDB()

parent aaf3b483
No related branches found
No related tags found
1 merge request!4Resolve "Configure MongoDB Connection"
Pipeline #15540 passed
const { MongoClient, Db } = require('mongodb'); const mongoose = require('mongoose');
const url = 'mongodb://localhost:27017/todo';
async function createCollections() { // Function to connect to MongoDB using Mongoose and create collections
try { async function connectDB() {
const client = new MongoClient(url); try {
await client.connect(); // Connect using the MongoDB URI from environment variables
const conn = await mongoose.connect("mongodb://127.0.0.1:27017");
console.log(`MongoDB connected: ${conn.connection.host}`);
// Check if the "todo" database exists and create it if not // Get the database object from the connection
const db = client.db('todo'); const db = conn.connection.db;
await db.createCollection('users'); // Check if collection "users" exists and create it if it doesn't exist
await db.createCollection('todos'); // Check if collection "todos" exists and create it if it doesn't exist
await db.createCollection('global'); // Check if collection "global" exists and create it if it doesn't exist
console.log('Collections created successfully!'); // Check if the collections exist and create them if not
await client.close(); await db.createCollection('users');
} catch (error) { await db.createCollection('todos');
console.error('Error creating collections:', error); await db.createCollection('global');
}
console.log('Collections created successfully!');
} catch (err) {
console.error(`Error: ${err.message}`);
process.exit(1); // Exit the process with failure if the connection or collection creation fails
}
} }
createCollections(); module.exports = connectDB;
\ No newline at end of file \ No newline at end of file
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment