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
async function connectDB() {
try { try {
const client = new MongoClient(url); // Connect using the MongoDB URI from environment variables
await client.connect(); 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 // Check if the collections exist and create them if not
await db.createCollection('global'); // Check if collection "global" exists and create it if it doesn't exist await db.createCollection('users');
await db.createCollection('todos');
await db.createCollection('global');
console.log('Collections created successfully!'); console.log('Collections created successfully!');
await client.close(); } catch (err) {
} catch (error) { console.error(`Error: ${err.message}`);
console.error('Error creating collections:', error); 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.
Please to comment