skip to Main Content

when i try to connect mongodb with nodejs express using a post method , where i just added a logger which will display a message database is connected if the nodejs listens to mongo db , but i found that though the post menthod is working the Mongoclient is not working thus the logger is not working,first i tried using (MongoClient.connect("mongodb://localhost:27017) this but it resulted in showing (MongooseServerSelectionError: connect ECONNREFUSED ::1:27017) in the console,so i have replaced the localhost with(MongoClient.connect(‘mongodb://127.0.0.1:27017’),now the result is is simply logging the console with the form inputs but still the app is not listening to mongodb please help me out iam totally a beginner

here is the code


var express = require('express');
var router = express.Router();
var MongoClient=require("mongodb").MongoClient
/* GET home page. */
router.get('/', function(req, res, next) {
  res.render('index', { title: 'Express' });
});
router.post('/',function(req,res,next){
  console.log(req.body);
  next
})
router.post("/submit",function(req,res) {
  console.log(req.body);

  MongoClient.connect('mongodb://127.0.0.1:27017',function(err,client){
    if(err)
      console.log('error')
    
    else
    console.log('database connected');
     client.db('bynode').collection("users").insertOne(req.body)
  })
  res.send("got it")
  
})

module.exports = router;

please help me iam stuck with my learning because of this
error

/error/
F:new spacenode_modulesmongodblibsdamtopology.js:278 const timeoutError = new error_1.MongoServerSelectionError(Server selection timed out after ${serverSelectionTimeoutMS} ms`, this.description);
^

MongoServerSelectionError: connect ECONNREFUSED ::1:27017
at Timeout._onTimeout (F:new spacenode_modulesmongodblibsdamtopology.js:278:38)
at listOnTimeout (node:internal/timers:569:17)
at process.processTimers (node:internal/timers:512:7) {
reason: TopologyDescription {
type: ‘Unknown’,
servers: Map(1) {
‘localhost:27017’ => ServerDescription {
address: ‘localhost:27017’,
type: ‘Unknown’,
hosts: [],
passives: [],
arbiters: [],
tags: {},
minWireVersion: 0,
maxWireVersion: 0,
roundTripTime: -1,
lastUpdateTime: 24984871,
lastWriteDate: 0,
error: MongoNetworkError: connect ECONNREFUSED ::1:27017
at connectionFailureError (F:new spacenode_modulesmongodblibcmapconnect.js:379:20)
at Socket. (F:new spacenode_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 ::1:27017
at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1495:16) {
errno: -4078,
code: ‘ECONNREFUSED’,
syscall: ‘connect’,
address: ‘::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,
[Symbol(errorLabels)]: Set(0) {},
[cause]: MongoNetworkError: connect ECONNREFUSED ::1:27017
at connectionFailureError (F:new spacenode_modulesmongodblibcmapconnect.js:379:20)
at Socket. (F:new spacenode_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 ::1:27017
at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1495:16) {
errno: -4078,
code: ‘ECONNREFUSED’,
syscall: ‘connect’,
address: ‘::1’,
port: 27017
}
}
}`

i tried changing the "MongoClient.connect("mongodb://localhost:27017" to "MongoClient.connect(‘mongodb://127.0.0.1:27017" the difference is that the error message of (MongooseServerSelectionError: connect ECONNREFUSED ::1:27017) was gone but the still the node was’t listening to mongodb , i was expecting the logger will display that "database is connected" ,also the form inputs will be stored to databse in bynode in that a collection users

2

Answers


  1. Your client connection should exist outside of your request response and you’re using outdated callback-style syntax. Mongo recommends you use ES Modules so that you have support for top-level await. There’s a whole tutorial here.

    const express = require('express');
    const router = express.Router();
    const { MongoClient } = require("MongoDB");
    
    const client = new MongoClient('mongodb://127.0.0.1:27017');
    await client.connect()
    
    router.post("/submit", async (req, res) => {
      // console.log(req.body);
      await client.db('bynode').collection("users").insertOne(req.body);
      res.send("got it")  
    })
    
    module.exports = router;
    
    Login or Signup to reply.
  2. I think you are missing name of the database in the connection string, You are providing localhost and port number in the connection string but you are not telling which collection the app should connect to.

    try to put your collection name in you string like this,

    'mongodb://127.0.0.1:27017/{your_collection_name}'
    

    hopefully it should work.

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