1

I'm encountering a server selection error when attempting to connect to my MongoDB database using Node.js on my Windows system. Specifically, I am using MongoDB version 6.0.6 and Node.js version 18.16.0. Although data is being sent to the server and successfully displayed on the terminal upon clicking the submit button on the signup form page, a connection to the database is not being established. I would greatly appreciate any insights or guidance on how to resolve this issue.

HERE IS MY index.js 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('/submit',function(req,res){
  console.log(req.body)
  MongoClient.connect("mongodb://localhost:27017",function(err,client){
    if(err)
      console.log('ERROR')
    else
      client.db('mydata').collection('user').insertOne(req.body)
  })

  res.send("Got it")
}) 
module.exports = router;

AND THE ERROR MESSAGE IN TERMINAL

POST /submit 200 31.648 ms - 6
[Object: null prototype] {
  first_name: 'tetew',
  last_name: 'fff',
  email: 'gggg',
  pw: 'fdf',
  pw_confirm: 'gg'
}
POST /submit 200 4.917 ms - 6
E:\Web\New Database\node_modules\mongodb\lib\sdam\topology.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 (E:\Web\New Database\node_modules\mongodb\lib\sdam\topology.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: 58231053,
        lastWriteDate: 0,
        error: MongoNetworkError: connect ECONNREFUSED ::1:27017
            at connectionFailureError (E:\Web\New Database\node_modules\mongodb\lib\cmap\connect.js:370:20)
            at Socket.<anonymous> (E:\Web\New Database\node_modules\mongodb\lib\cmap\connect.js:293:22)
            at Object.onceWrapper (node:events:628:26)
            at Socket.emit (node:events:513: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) {
          cause: Error: connect ECONNREFUSED ::1:27017
[nodemon] app crashed - waiting for file changes before starting...
  • Does this answer your question? [MongooseServerSelectionError: connect ECONNREFUSED ::1:27017](https://stackoverflow.com/questions/69840504/mongooseserverselectionerror-connect-econnrefused-127017) – rickhg12hs May 16 '23 at 08:55

1 Answers1

0
connect ECONNREFUSED ::1:27017

your connection failed trying to connect via the ipv6 of localhost (::1)

Check if your server is set to run on both ipv4 (127.0.0.1) and ipv6 of localhost in your mongod.cfg file under

net: 
  bindIp: 127.0.0.1, ::1
  ipv6: true
lumikso
  • 3
  • 3
  • I have made the changes in mongod.cfg as you said. Should I add or make any correction on connection url to get connected to database and printed that "We are connected" in console. router.post('/submit',function(req,res){ console.log(req.body) MongoClient.connect("mongodb://127.0.0.1:27017/exampleDb", function(err, db) { if(!err) { console.log("We are connected"); }}); res.send("got it") }) module.exports = router; – FEBIN DEVASSIA May 16 '23 at 14:15
  • If you listed both the ipv4 and ipv6 of locahost in the config file as above, then you just need `MongoClient.connect("mongodb://localhost:27017/exampleDb")` – lumikso May 16 '23 at 20:36