Metz
Metz
JCHJava Community | Help. Code. Learn.
Created by Metz on 11/26/2024 in #java-help
Connecting to my MongoDB Database
Hello everyone, I am struggling to find the reason why I cant connect with my database on MongoDB. This is my first project on java ever and it is going to be an App. I think I have the wrong line of code for the connection I intended to use on MongoDB and I kinda got confused with all the Methods. I am using VS Code and I think using the MongoDB extension on VS is the most practical going forward. So if anyone has some experience working with these tools I would appreciate the help. When trying to run the server this is the error message iI get querySrv ENOTFOUND _mongodb._tcp.cluster0.mongodb.net and this is the line on my .env i am using to connect to MongoDB MONGO_URI=mongodb+srv://mmetinbirguel:[email protected]/Tierlist?retryWrites=true&w=majority Of course I have my real password instead of just "password" there, for safety reasons I share it like this 😄 this is the database.js I have:
const mongoose = require('mongoose');

const connectDB = async () => {
try {
await mongoose.connect(process.env.MONGO_URI); // No need for options now
console.log('MongoDB Connected...');
} catch (err) {
console.error(err.message);
process.exit(1);
}
};

module.exports = connectDB;
const mongoose = require('mongoose');

const connectDB = async () => {
try {
await mongoose.connect(process.env.MONGO_URI); // No need for options now
console.log('MongoDB Connected...');
} catch (err) {
console.error(err.message);
process.exit(1);
}
};

module.exports = connectDB;
` and this is on my root index.js to connect with mongodb:
// Initialize environment variables
const dotenv = require('dotenv');
dotenv.config(); // Make sure this is called at the very top
console.log(process.env.MONGO_URI); // Log the MongoDB URI


const express = require('express');
const connectDB = require('./database'); // Database connection
// Initialize environment variables
const dotenv = require('dotenv');
dotenv.config(); // Make sure this is called at the very top
console.log(process.env.MONGO_URI); // Log the MongoDB URI


const express = require('express');
const connectDB = require('./database'); // Database connection
Thank you in advance if you need any more information let me know.
14 replies