0

I am trying to connect to my backend mongodb 5.0.5 with nodejs express script. when running the app.js using nodemon it shows your mongodb is connected but on the localhost it keeps on reloading without any error stack trace.

I am using mongoose models in the models as in MVC in nodejs. Not sure why its is not getting run on localhost, it was working fine when last I used these files.

here are my files:

app.js

// imports
  const express = require('express')
 const bodyParser = require('body-parser')
 const cors = require('cors')
 const { append } = require('express/lib/response')
  const zomatoRoutes = require('./Routes/zomato')
  const mongoose = require('mongoose')

     // create express server

     var app = express()

     //listen to a port

     app.listen(7878, () => {
       console.log('app running on port 7878');
   })

     app.use(bodyParser.json())

    //connect mongodb   
    mongoose.connect('mongodb://localhost/zomato', () => {
  console.log("MongoDB Connected");},
   e => console.log(e)
   ) 

   // Middleware routes
   app.use('/zomato', zomatoRoutes)

   app.use(cors())

Model > locations.js

const mongoose = require('mongoose')

const locationSchema = new mongoose.Schema({

name: {
    type: String,
    required:true  
},
city_id: {
    type: String,
    required:true
},
location_id: {
    type: String,
    required:true
},
country_name: {

    type: String,
    required:true
   }

  })

  module.exports = mongoose.model("LocationsModel", locationSchema, "locations")

Controllers > location.js

const { status } = require('express/lib/response')
const Locations = require('../Model/location')

 exports.getAllLocations = (req, res) => {
   Locations.find().then(
    result => {

        res.status(200).json({ message: "data fetched successfully", data: result })
    }
).catch(error => {

    res.send(500).json({ message: "Error in Database", error: error })
  })
}

and my routes

zomato.js

const express = require('express')
const Router = express.Router();
const RestaurantController = require('../Controller/Restaurant')
const LocationsController = require('../Controller/Location')

  // configure routes

    // Restaurants routes
  Router.get('/restaurants', RestaurantController.getAllRestaurants)


  Router.post('/restaurants/filter/:pageNo', RestaurantController.getRestaurantsByFilter)


  // Locations routes

  Router.get('/locations', LocationsController.getAllLocations)

  module.exports = Router

my Json files locations.json goes like this:

[
{
    "_id": "1",
    "name": "ShalimarBhagh, Delhi",
    "city_id": "1",
    "location_id": "1",
    "country_name": "India"
},
{
    "_id": "2",
    "name": "Janpat, Delhi",
    "city_id": "1",
    "location_id": "2",
    "country_name": "India"
},
{
    "_id": "3",
    "name": "MSP, Delhi",
    "city_id": "1",
    "location_id": "3",
    "country_name": "India"
}
]

** Updates: I forgot to mention I recently updated to windows10 to make sure my react app works and after this issue is arising, now I created a fresh application with removing mongo and re-installing mongodb still gets me this error in postman Error: read ECONNRESET**

err pic

Update I get this stack trace

C:\Users\acer\Documents\EDUREKA\Nodejs-mongodb- 
 mongoose\node_modules\mongoose\lib\connection.js:797
 const serverSelectionError = new ServerSelectionError();
                           ^
    MongooseServerSelectionError: connect ECONNREFUSED ::1:27017
  at NativeConnection.Connection.openUri 
 (C:\Users\acer\Documents\EDUREKA\Nodejs-mongodb- 
  umongoose\node_modules\mongoose\lib\connection.js:797:32)
Vishal Torne
  • 366
  • 5
  • 24

2 Answers2

0

Try this instead:

// imports
const express = require('express')
const bodyParser = require('body-parser')
const cors = require('cors')
const { append } = require('express/lib/response')
const zomatoRoutes = require('./Routes/zomato')
const mongoose = require('mongoose')

 // create express server
 const app = express()

 // Middleware routes
 app.use(cors())
 app.use(bodyParser.json())
 app.use('/zomato', zomatoRoutes)

 //connect mongodb   
 mongoose.connect('mongodb://localhost/zomato', () => {
   console.log("MongoDB Connected");
   const server = app.listen(7878, () => {
      console.log('app running on port 7878');
   })
  server.setTimeout(0) // disable the default time out server mechanism
  },
  e => console.log(e)
 ) 

Which is:

  • initialize exprress app
  • register middlewares
  • connect to mongo
  • if connection successful (and only then) - start the application

Also, replace your code

res.status(200).json({ data: 'whatever' })

to:

res.status(200).send({ data: 'whatever' })

There is a chance that your response is not getting back to client, hence - resulting in timeout error. This approach should fix this as well

Hope it will help you with your problem

ymz
  • 6,602
  • 1
  • 20
  • 39
  • Thank you for your help bro. But have the issues. I recently updated to Windows 10. After that is it not working I created a new fresh app and it gets error like in Postman : Error: read ECONNRESET – Vishal Torne Jan 19 '22 at 22:30
0

Localhost is not resolved, though I changed my mongodb to ipv6 using mongod --ipv6 still it does not accept and in stack trace shows isIPV6 : false.

so finally I had to change the using the answer here listen to port using ipv4

//connect to mongoDB
 const uri = 'mongodb://localhost:27017/zomato';

 const options = {
 useNewUrlParser: true,
 useUnifiedTopology: true,
 family:4
 }

 const connectWithDB = () => {
 mongoose.connect(uri, options, (err, db) => {
  if (err) console.error(err);
  else console.log("database connection")
})
}

 connectWithDB()

It is working now and fetching data but want to resolve the issue of ipv6 nodejs.

Vishal Torne
  • 366
  • 5
  • 24