shrlckphn
shrlckphn

Reputation: 3

Failing to connect mongodb atlas with nodejs

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 Setups\backend setups\cheezy code\node_modules\mongodb\lib\connection_string.js:52:15)
    at D:\Other Setups\backend setups\cheezy code\node_modules\mongodb\lib\mongo_client.js:120:78
    at maybeCallback (D:\Other Setups\backend setups\cheezy code\node_modules\mongodb\lib\utils.js:337:21)
    at MongoClient.connect (D:\Other Setups\backend setups\cheezy code\node_modules\mongodb\lib\mongo_client.js:114:42)
    at D:\Other Setups\backend setups\cheezy code\node_modules\mongoose\lib\connection.js:809:12
    at new Promise (<anonymous>)
    at NativeConnection.Connection.openUri (D:\Other Setups\backend setups\cheezy code\node_modules\mongoose\lib\connection.js:798:19)
    at D:\Other Setups\backend setups\cheezy code\node_modules\mongoose\lib\index.js:413:10
    at D:\Other Setups\backend setups\cheezy code\node_modules\mongoose\lib\helpers\promiseOrCallback.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.

Upvotes: 0

Views: 252

Answers (3)

jeraldlashie
jeraldlashie

Reputation: 101

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

Upvotes: 0

Sarthak Agarwal
Sarthak Agarwal

Reputation: 53

"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"

Upvotes: 0

Serhii Chyzhyk
Serhii Chyzhyk

Reputation: 122

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.

Upvotes: 0

Related Questions