简体   繁体   中英

Not able to connect to mongodb Atlas cluster from nodejs(express) simple app

I created a simple node and express app. I am trying to connect to my cluster on atlas but it always fails to connect.

Following is my index.js file :

const express = require("express");
const mongoose = require("mongoose");
const bodyParser = require("body-parser");

var cors = require("cors");

mongoose.Promise = global.Promise;

// create express app
const app = express();

app.use(cors());

// parse requests of content-type - application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: true }));

// parse requests of content-type - application/json
app.use(bodyParser.json());

const url = "mongodb+srv://<username>:<password>@cluster1-n60yg.mongodb.net/test";

//Connecting to the database
mongoose
  .connect(url, {
    dbName: "testdb"
  })
  .then(() => {
    console.log("Successfully connected to the database");
  })
  .catch(err => {
    console.log("Could not connect to the database. Exiting now...", err);
    process.exit();
  });

// define a simple route
app.get("/", (req, res) => {
  res.json({ message: "this will br crud" });
});

// listen for requests
app.listen(3000, () => {
  console.log("Server is listening on port 3000");
});

After about 1-2 minutes after I run the code, this error is thrown:

Could not connect to the database. Exiting now... { MongoNetworkError: failed to connect to server [cluster1-shard-00-00-n60yg.mongodb.net:27017] on first connect [MongoNetworkError: connection timed out]
    at Pool.<anonymous> (/home/nikhil/Documents/node-graphql-mongo-crud/node_modules/mongodb-core/lib/topologies/server.js:431:11)
    at emitOne (events.js:116:13)
    at Pool.emit (events.js:211:7)
    at connect (/home/nikhil/Documents/node-graphql-mongo-crud/node_modules/mongodb-core/lib/connection/pool.js:557:14)
    at makeConnection (/home/nikhil/Documents/node-graphql-mongo-crud/node_modules/mongodb-core/lib/connection/connect.js:39:11)
    at callback (/home/nikhil/Documents/node-graphql-mongo-crud/node_modules/mongodb-core/lib/connection/connect.js:261:5)
    at TLSSocket.err (/home/nikhil/Documents/node-graphql-mongo-crud/node_modules/mongodb-core/lib/connection/connect.js:286:7)
    at Object.onceWrapper (events.js:313:30)
    at emitNone (events.js:106:13)
    at TLSSocket.emit (events.js:208:7)
    at TLSSocket.Socket._onTimeout (net.js:422:8)
    at ontimeout (timers.js:498:11)
    at tryOnTimeout (timers.js:323:5)
    at Timer.listOnTimeout (timers.js:290:5)
  name: 'MongoNetworkError',
  errorLabels: [ 'TransientTransactionError' ],
  [Symbol(mongoErrorContextSymbol)]: {} }

This code works in a sandbox (ie It is connecting successfully). But for some reason, I can't connect it from my laptop (I am using Ubuntu 18.04). I am behind a corporate proxy. But I tried this with mobile data (cellular network) and it still doesn't work. I have already whitelisted all IPs (0.0.0.0/0) in Network access setting in mongodb atlas.

I saw the docs and found this in "Network and Firewall requirements":

If you use a whitelist on your firewall for network ports, open ports >27015 to 27017 to TCP and UDP traffic on Atlas hosts. This grants your >applications access to databases stored on Atlas.

Is this step is what I am missing? Please suggest solutions to this problem.

EDIT I got it working on mobile data but still can't connect through corporate proxy. Any working solutions?

确保您在查询中使用了正确的用户名和密码,而且看起来您的数据库名称是 testdb 并且在查询中确保您将“test”替换为“testdb”

const url = "mongodb+srv://<username>:<password>@cluster1-n60yg.mongodb.net/testdb";

I just copied your code and ran against my own mongodb instance and changed the url as

const url = "mongodb+srv://admin:PASSWORD@cluster1-n60yg.mongodb.net/test?retryWrites=true";

and it worked and it printed the output " Successfully connected to the database ".

I whitelisted my IP address, (found out it had changed earlier) or you can just go on and accept any random IP.

I also placed the connection inside an asynchronous function.

Code:

// ======================== db configurations===========================//
mongoose.Promise = global.Promise;

const connectDB = async () => {
    mongoose.connect(db.url, db.options);
    console.log('DB Connected....');
};

connectDB();

hope this helps, happy hacking!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM