ReNinja
ReNinja

Reputation: 573

MongoDb connection with Node js

I need to setup Mongo DB with my nodejs application . I created an account in mongoDb Atlas and I am trying to connect my app with the below URL with my username and password . Unfortunately I am getting authentication Fail error .

const MongoClient = require("mongodb").MongoClient;


const CONNECTION_URL = "mongodb+srv://<username>:<password>@renj0-2herp.mongodb.net/test?retryWrites=true";
const DATABASE_NAME = "example";

var app = Express();

app.use(BodyParser.json());
app.use(BodyParser.urlencoded({ extended: true }));

var database, collection;

app.post("/person", (request, response) => {
    collection.insert(request.body, (error, result) => {
        if(error) {
            return response.status(500).send(error);
        }
        response.send(result.result);
    });
});

app.get("/people", (request, response) => {
    collection.find({}).toArray((error, result) => {
        if(error) {
            return response.status(500).send(error);
        }
        response.send(result);
    });
});

app.listen(3001, () => {
    MongoClient.connect(CONNECTION_URL, { useNewUrlParser: true }, (error, client) => {
        if(error) {
            throw error;
        }
        database = client.db(DATABASE_NAME);
        collection = database.collection("people");
        console.log("Connected to `" + DATABASE_NAME + "`!");
    });
});

Upvotes: 0

Views: 139

Answers (2)

Kuldip Shukla
Kuldip Shukla

Reputation: 21

const CONNECTION_URL = 'mongodb://username:password@localhost:27017/example'

Your connection url is wrong so i suggest you try this format or try below also

const CONNECTION_URL = 'mongodb://localhost:27017/example'

Upvotes: 2

sopan mittal
sopan mittal

Reputation: 45

you need to whitelist your IP adders with MongoDb Atlas. To do so, open cmd/terminal and run command "ipconfig" and search for "IPv4 Address" and copy the IP address. Now, open your Atlas cluster, goto security, and there you will find the option IP whitelist, click ADD IP ADDRESS and add you IP.

Upvotes: 1

Related Questions