skip to Main Content

I am creating a simple application on Nodejs as a beginner. I am failing to connect nodejs with mongodb atlas. Kindly help me.
I have provided the username, password and clustername respectively.

const express = require("express");
const app = express();
const userRouter = require("./routes/userRoutes");
const noteRouter = require("./routes/userRoutes");

const mongoose = require("mongoose");

app.use("/users", userRouter);
app.use("notes", noteRouter);

app.get("/", (req, res) => {
  res.send("Hello");
});


mongoose
  .connect(
    "mongodb+srv://username:[email protected]/?retryWrites=true&w=majority"
  )
  .then(() => {
    app.listen(5000, () => {
      console.log("server started on port no. 5000");
    });
  })
  .catch((err) => {
    console.log(err);
  });

The error I am getting is :

MongoAPIError: URI must include hostname, domain name, and tld
    at resolveSRVRecord (D:Other Setupsbackend setupscheezy codenode_modulesmongodblibconnection_string.js:52:15)
    at D:Other Setupsbackend setupscheezy codenode_modulesmongodblibmongo_client.js:120:78
    at maybeCallback (D:Other Setupsbackend setupscheezy codenode_modulesmongodblibutils.js:337:21)
    at MongoClient.connect (D:Other Setupsbackend setupscheezy codenode_modulesmongodblibmongo_client.js:114:42)
    at D:Other Setupsbackend setupscheezy codenode_modulesmongooselibconnection.js:809:12
    at new Promise (<anonymous>)
    at NativeConnection.Connection.openUri (D:Other Setupsbackend setupscheezy codenode_modulesmongooselibconnection.js:798:19)
    at D:Other Setupsbackend setupscheezy codenode_modulesmongooselibindex.js:413:10
    at D:Other Setupsbackend setupscheezy codenode_modulesmongooselibhelperspromiseOrCallback.js:41:5
    at new Promise (<anonymous>) {
  [Symbol(errorLabels)]: Set(0) {}
}
[nodemon] clean exit - waiting for changes before restart

I was expecting a successful connection between mongodb and nodejs. With the output "server started on port no. 5000" in the console.

3

Answers


  1. See the format of the connection string here:

    https://www.mongodb.com/docs/manual/reference/connection-string/

    in your case, copy the connection string from MongoDB and replace username and password with your own.

    Login or Signup to reply.
  2. "mongodb+srv://username:[email protected]/?retryWrites=true&w=majority"

    So in this link, you should include the database name as well, which I think you might have forgotten.

    Try the URI like this :
    "mongodb+srv://username:password@clustername.ox93pg1.mongodb.net/databaseName?retryWrites=true&w=majority"

    Login or Signup to reply.
  3. I’m not sure if you have your username and password set correctly. If not then you can achieve this by using the .env file.

    1. install the dotenv using npm
    2. import like require('dotenv').config();
    3. create a .env file and add the username and password
    4. import then using process.env.{name}

    Secondly, while you are learning separate database connection from starting your app (just a suggestion as shown and use exit to terminate your app if database fails.)

    Make sure your link is working (get it as it is from atlas)
    Create a db on atlas you will get the correct link. Your link shows cluster name meaning you just copied the link from somewhere other than your cluster name Unless you masked this out for security reasons.

    const express = require("express");
    const app = express();
    const userRouter = require("./routes/userRoutes");
    const noteRouter = require("./routes/userRoutes");
    
    //npm install dotenv and import it
    // create a .env file and import username, password and PORT for database
    require('dotenv').config();
    
        const mongoose = require("mongoose");
        username = process.env.USERNAME
        password = process.env.PASSWORD
        console.log(password)
        
        //get your url for mongodb atlas and add password and username from the .env
        mongoose.connect(`mongodb+srv://${username}:${password}@clustername.ox93pg1.mongodb.net/?retryWrites=true&w=majority`)
            .then(() => console.log('Connected…'))
            .catch(err => console.error('Connection failed…'));
        
        
        app.use("/users", userRouter);
        app.use("/notes", noteRouter);
        
        app.get("/", (req, res) => {
          res.send("Hello");
        });
        
        const PORT = process.env.PORT || 5000;
        app.listen(PORT, ()=> {
            console.log(`Listening on http://localhost:${PORT}`)
        });
    

    Then you .env as following

    PORT = 6000
    USERNAME = lashie
    PASSWORD = lashie
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search