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...