1

I am new in mongodb and currently following this article: https://medium.com/@beaucarnes/learn-the-mern-stack-by-building-an-exercise-tracker-mern-tutorial-59c13c1237a1

I am using mongoDB atlas as a course suggested and also whitelist my IP in it as many answers suggested.

File: .env

ATLAS_URI=mongodb+srv://sagar:<mypass>@cluster0-2gcdi.gcp.mongodb.net/test?retryWrites=true&w=majority

server.js

const express = require('express');
const cors = require('cors');
const mongoose = require('mongoose');

require('dotenv').config();

const app = express();
const port = process.env.PORT || 5000;

app.use(cors());
app.use(express.json());

const uri = process.env.ATLAS_URI;
mongoose.connect(uri, { useUnifiedTopology: true, useNewUrlParser: true, useCreateIndex: true }
);
const connection = mongoose.connection;
connection.once('open', () => {
  console.log("MongoDB database connection established successfully");
})

const usersRouter = require('./routes/users');

app.use('/users', usersRouter);

app.listen(port, () => {
    console.log(`Server is running on port: ${port}`);
});

user.model.js

const mongoose = require('mongoose');

const Schema = mongoose.Schema;

const userSchema = new Schema({
  username: {
    type: String,
    required: true,
    unique: true,
    trim: true,
    minlength: 3
  },
}, {
  timestamps: true,
});

const User = mongoose.model('User', userSchema);

module.exports = User;

routes:users.js

const router = require('express').Router();
let User = require('../models/user.model');

router.route('/').get((req, res) => {
  User.find()
    .then(users => res.json(users))
    .catch(err => res.status(400).json('Error: ' + err));
});

router.route('/add').post((req, res) => {
  const username = req.body.username;

  const newUser = new User({username});

  newUser.save()
    .then(() => res.json('User added!'))
    .catch(err => res.status(400).json('Error: ' + err));
});

module.exports = router;

currently its showing Error in console:

UnhandledPromiseRejectionWarning: MongooseTimeoutError: Server selection timed out after 30000 ms at new MongooseTimeoutError (C:\Users\sagar\OneDrive\Desktop\nodejs\mern-exercise-tracker\backend\node_modules\mongoose\lib\error\timeout.js:22:11)

I am also testing my api in postman where its showing:

Could not get any response There was an error connecting to http://localhost:5000/users/add.

Error of my screenshot: enter image description here

Sagar Parikh
  • 288
  • 5
  • 20

0 Answers0