Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

mongo database name not changing

im working with express.js, mongodb, and mongoose, all my dbs are defaulted to "test" and i seem unable to decide/change what the name is, resulting in all my projects getting connected to the same db

my .env file:

PORT=8000
DB=productmanager
ATLAS_USERNAME=root
ATLAS_PASSWORD=root

my mongoose.config.js:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

const mongoose = require("mongoose");
const username = process.env.ATLAS_USERNAME;
const password = process.env.ATLAS_PASSWORD;
const uri = `mongodb+srv://${username}:${password}@codingdojo.v7stzvz.mongodb.net/?retryWrites=true&w=majority`;

mongoose.connect(uri)
    .then(() => console.log("Established a connection to the database"))
    .catch(err => console.log("Something went wrong when connecting to the database", err));

this will create a "test" db in my "codingdojo" cluster

i tried manuallu creating the db with the name i desire but failed to connect my server to it

>Solution :

In your Mongoose configuration, the issue is arising because you’re not specifying the name of the database you want to connect to in the connection URI. By default, when you don’t specify a database name in the URI, Mongoose will connect to the "test" database.

To connect to a specific database, you should include the database name in the URI like this:

const mongoose = require("mongoose");
const username = process.env.ATLAS_USERNAME;
const password = process.env.ATLAS_PASSWORD;
const dbName = process.env.DB; // This is the name of the database you want to connect to
const uri = `mongodb+srv://${username}:${password}@codingdojo.v7stzvz.mongodb.net/${dbName}?retryWrites=true&w=majority`;

mongoose.connect(uri)
    .then(() => console.log("Established a connection to the database"))
    .catch(err => console.log("Something went wrong when connecting to the database", err));

With this change, your DB environment variable will determine the name of the database to which Mongoose will connect. Make sure your .env file has the correct value for DB set to the desired database name, such as "productmanager."

After making this change, Mongoose will connect to the specified database, and you should no longer be connecting to the "test" database by default.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading