skip to Main Content

Actually, i am learning Node JS, Mongodb and Express JS. so i was just trying to make a db with Mongodb compass and store some data in it. but when i am trying to run my code then my nodemon server is crashing again and again few minutes after starting the server.

So here is the code of main files –

app.js –

var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
const expressession = require('express-session');
const flash = require('connect-flash');

var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');

var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');

app.use(expressession({
  resave:false,
  saveUninitialized: false,
  secret: 'secretcode671'
}));

app.use(flash());


// is code ne meri gaand maar li hai 

app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

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

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  next(createError(404));
});

// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});

module.exports = app;

user.js –

const mongoose = require('mongoose');

mongoose.connect("mongodb://127.0.0.1:27017/testing2");

const userschema =  mongoose.Schema({
  username: String,
  nickname: String,
  description: String,

  categories: {
    type: Array,
    default: []
  },
  datecreated: {
    type: Date,
    default: Date.now()
  }
})

module.exports = mongoose.model("user", userschema)

index.js –

const { name } = require('ejs');
var express = require('express');
var router = express.Router();
const usermodel = require('./users')

/* GET home page. */
router.get('/', function(req, res, next) {
  res.render('index', { title: 'Express' });
});

 router.get('/create', async function(res,req){
  let userdata = await usermodel.create({
    username: "shadow",
    nickname: "Teju",
    description: "Hello i am a guy who is learning programming",
  
    categories: ['js','nodejs','react','gsap','express', 'mongodb'],
   
  })
  res.send(userdata);
 })
module.exports = router;

I have wrote this code in order to make a db and store some data in it for my learning and practice purpose.
When i run this on localhost:3000 with the "npx nodemon" command so the server gets started and i come on the index file of this website, everything works fine til here. But when i try to go to /create route by this url – "localhost:3000/create" so it keeps loading for a few seconds and then server gets crashed. after server crash i get the following error in my terminal –
C:UsersuserDesktopTejashvProgramming filesPracticemyappnode_modulesmongooselibconnection.js:875
err = new ServerSelectionError();
^

MongooseServerSelectionError: connect ECONNREFUSED 127.0.0.1:27017
at _handleConnectionErrors (C:UsersuserDesktopTejashvProgramming filesPracticemyappnode_modulesmongooselibconnection.js:875:11)
at NativeConnection.openUri (C:UsersuserDesktopTejashvProgramming filesPracticemyappnode_modulesmongooselibconnection.js:826:11) {
reason: TopologyDescription {
type: ‘Unknown’,
servers: Map(1) {
‘127.0.0.1:27017’ => ServerDescription {
address: ‘127.0.0.1:27017’,
type: ‘Unknown’,
hosts: [],
passives: [],
arbiters: [],
tags: {},
minWireVersion: 0,
maxWireVersion: 0,
roundTripTime: -1,
lastUpdateTime: 56995928,
lastWriteDate: 0,
error: MongoNetworkError: connect ECONNREFUSED 127.0.0.1:27017
at connectionFailureError (C:UsersuserDesktopTejashvProgramming filesPracticemyappnode_modulesmongodblibcmapconnect.js:379:20)
at Socket. (C:UsersuserDesktopTejashvProgramming filesPracticemyappnode_modulesmongodblibcmapconnect.js:285:22)
at Object.onceWrapper (node:events:629:26)
at Socket.emit (node:events:514:28)
at emitErrorNT (node:internal/streams/destroy:151:8)
at emitErrorCloseNT (node:internal/streams/destroy:116:3)
at process.processTicksAndRejections (node:internal/process/task_queues:82:21) {
[Symbol(errorLabels)]: Set(1) { ‘ResetPool’ },
[cause]: Error: connect ECONNREFUSED 127.0.0.1:27017
at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1595:16) {
errno: -4078,
code: ‘ECONNREFUSED’,
syscall: ‘connect’,
address: ‘127.0.0.1’,
port: 27017
}
},
topologyVersion: null,
setName: null,
setVersion: null,
electionId: null,
logicalSessionTimeoutMinutes: null,
primary: null,
me: null,
‘$clusterTime’: null
}
},
stale: false,
compatible: true,
heartbeatFrequencyMS: 10000,
localThresholdMS: 15,
setName: null,
maxElectionId: null,
maxSetVersion: null,
commonWireVersion: 0,
logicalSessionTimeoutMinutes: null
},
code: undefined
}

Node.js v20.5.1
[nodemon] app crashed – waiting for file changes before starting…

I even tried to go to Mongodb Compass in order to see if i can do something in this and when i try to connect the database i get the follow error there – connect ECONNREFUSED 127.0.0.1:27017

Can someone please help me by telling what is the cause of this problem and how to solve it. I would be really thankful to you if you can help me

2

Answers


  1. The ECONNREFUSED 127.0.0.1:27017 error indicates that there is no application currently listening on that port and IP.

    You are trying to connect to a MongoDB database. Make sure it is installed and running at port 27017

    Login or Signup to reply.
  2. This is my answer as a checking of my api

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search