diff --git a/mongodb.js b/mongodb.js index 37662f0f05160caf7a8ee2de34eb663bbbb0a564..d5c632a1d9002743b1a03bbaa452d9ec26e5d920 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