1
votes

I have created MongoDB Atlas account, and tried to connect. But got the error below.

MongoDB connection error MongoNetworkError: failed to connect to server [cluster0-shard-00-00-c487z.mongodb.net:27017] on first connect [MongoNetworkError: connection 5 to cluster0-shard-00-00-c487z.mongodb.net:27017 closed .......]

Here is my code.

const mongoose = require('mongoose');
const express = require('express');
var cors = require('cors');
const bodyParser = require('body-parser');
const logger = require('morgan');
const Data = require('./data');
const API_PORT = 3001;
const app = express();
app.use(cors());
const router = express.Router();
const dbRoute = 'mongodb+srv://<username>:<Password>@cluster0-c487z.mongodb.net/fullstack_app';
mongoose.connect(dbRoute, {useNewUrlParser: true});
let db = mongoose.connection;
db.once('open', () => console.log('connected to the database'));
db.on('error', console.log.bind(console, 'MongoDB connection error'));
router.post('/putData', (req, res) => {
    let data = new Data();
    const { id, message } = req.body;
    if ((!id && id !== 0) || !message) {
      return res.json({
        success: false,
        error: 'INVALID INPUTS',
      });
    }
    data.message = message;
    data.id = id;
    data.save((err) => {
      if (err) return res.json({ success: false, error: err });
      return res.json({ success: true });
    });
  });

  app.use('/api', router);
  app.listen(API_PORT, () => console.log(`LISTENING ON PORT ${API_PORT}`));
1

1 Answers

0
votes

Login to your atlas account and click "Connect" on the "Clusters" tab enter image description here

Select "Connect application"

enter image description here

Choose language and driver version (node.js driver 3.0+ on the screenshot) and copy the connection string to use in your application:

enter image description here

Ensure you read and comprehend the smallprint - you will need to replace login and password with actual values.

Then go to "Network" tab and click "Add IP":

enter image description here

Then click "Add current IP" to access the cluster from your current system or add an IP of your server that hosts your application manually:

enter image description here