getting this error MongooseError: Operation `contacts.insertOne()` buffering timed out after 10000ms after deploying the application on Heroku

Viewed 23

I am working on an application. In which I am using Nodejs, Expressjs and Mongodb(atlas) . Post method is working fine with localhost and Postman but after deploying the application on Heroku getting above error. Please help me , thanks in advance.

This is the image of my folder structure. folder structure

/src/db/connect.js :

require('dotenv').config();
const mongoose = require('mongoose');
mongoose.connect(process.env.HOST,{useNewUrlParser:true, useUnifiedTopology : true})
.then(() => console.log('connection successful'))
.catch((err) => console.log('Error :' +err));

.env file :

HOST=mongodb+srv://myid:mypassword@cluster0.h6y89rp.mongodb.net/portfolio?retryWrites=true&w=majority

(using my ID and password instead of 'myid:mypassword' in original code )

/src/modals/user.js :

const mongoose = require('mongoose');
const validator = require('validator');
const portfolioSchema = new mongoose.Schema({
  name : 
   {
    type : String,
    minlength : 3,
    maxlength : 50,
    required : true,
    validate(value)
    {
        if(validator.isNumeric(value))
        {
            throw new Error("Name should be alphabatic");
        }
    }
},    email :
 {
    type : String,
    required : true,
    validate(value)
    {
        if(!validator.isEmail(value))
        {
            throw new Error('Email not valid');
        }
    }
},
message : {
    type : String
}})
module.exports = new mongoose.model('contact',portfolioSchema);

src/app.js :

require('dotenv').config();
const express = require('express');
const app = express();
require('./db/connect');
const user = require('./modals/user');
const port = process.env.PORT || 5000;
const path = require('path');
const public = path.join(__dirname,'../public');

app.use(express.urlencoded({extended : false}));
app.use(express.json());
app.use(express.static(public));

app.set('view engine','hbs');

app.get('/',(req,res)=>{
res.render('index')//views--> hbs file
})

app.post('/',async(req,res)=>
{
const data = new user(req.body);
try{
   
     const result = await data.save();
     res.status(201).send(`your data is added , We will contact you soon have nice day :)`);
   
     }
     catch(err)
     {
      res.status(400).send('Something went wrong'+err);
     }

     })
    app.listen(port,() =>{
    console.log('server is started at '+port)
     });

Form data is in this file views/index.hbs :

 <div class="col-lg-6 col-md-6 col-12">
                <form action="/" method="post" class="contact-form webform" role="form">

                    <div class="form-group d-flex flex-column-reverse">
                        <input type="text" class="form-control" name="name" id="name" placeholder="Your Name">

                        <label for="cf-name" class="webform-label">Full Name</label>
                    </div>

                    <div class="form-group d-flex flex-column-reverse">
                        <input type="email" class="form-control" name="email" id="email"
                            placeholder="Your Email">

                        <label for="cf-email" class="webform-label">Your Email</label>
                    </div>

                    <div class="form-group d-flex flex-column-reverse">
                        <textarea class="form-control" rows="5" name="message" id="message"
                            placeholder="Your Message"></textarea>

                        <label for="cf-message" class="webform-label">Message</label>
                    </div>

                    <button type="submit" class="form-control" id="submit-button" name="submit">Send</button>
                </form>
            </div>

Scripts in package.json file :

"dev" : "nodemon src/app.js -e hbs,js,html",
"start" : "node src/app.js -e hbs,js,html"

both requests are working in postman :

get request in postman post request in postman

1 Answers

I understood what is wrong with above application.

When we are deploying application on Heroku. We should add our 'mongodb atlas / database url' to heroku which is present in '.env file' env file image . Due to security purpose we are not uploading that file, so we need to make sure we are using the 'mongodb atlas / database url' in Heroku for our database connection .

Here are the steps to add mongodb url in Heroku:

1.Login to Heroku(on browser).

2.click on your application name.

3.Click on settings tab. Settings tab image

4.Click on Reveal Config Vars.

5.There are two fields 'KEY' and 'VALUE'. In key field add key like in .env file. In this case key will be 'HOST' and in value field add the mongodb url like given in the following image. key value in HEROKU image

Related