From b814678f03c9d9afa88a0fdc974727df826bbe66 Mon Sep 17 00:00:00 2001 From: strokh24 <Rokas.Stankunas@Student.Reutlingen-University.DE> Date: Sun, 6 Oct 2024 20:01:40 +0200 Subject: [PATCH] refactored function into connectDB() --- mongodb.js | 37 ++++++++++++++++++++----------------- 1 file changed, 20 insertions(+), 17 deletions(-) diff --git a/mongodb.js b/mongodb.js index 37662f0..d5c632a 100644 --- a/mongodb.js +++ b/mongodb.js @@ -1,22 +1,25 @@ -const { MongoClient, Db } = require('mongodb'); -const url = 'mongodb://localhost:27017/todo'; +const mongoose = require('mongoose'); -async function createCollections() { - try { - const client = new MongoClient(url); - await client.connect(); +// Function to connect to MongoDB using Mongoose and create collections +async function connectDB() { + try { + // 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 - const db = client.db('todo'); - 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 + // Get the database object from the connection + const db = conn.connection.db; - console.log('Collections created successfully!'); - await client.close(); - } catch (error) { - console.error('Error creating collections:', error); - } + // Check if the collections exist and create them if not + await db.createCollection('users'); + await db.createCollection('todos'); + 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(); \ No newline at end of file +module.exports = connectDB; \ No newline at end of file -- GitLab