Search code examples
javascriptmongodbexpressmongoose

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:

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