0
import express from 'express'
const app = express();
const port = process.env.PORT || 8000;

import mongoose from 'mongoose';

mongoose.connect("mongodb://localhost:27017/schooldb").then(() => {
    console.log("connection successfully ");
})
app.get('/', (req, res) => {
    res.send('Hello user')
})

app.listen(port, () => {
    console.log(`listening at port http://localhost:${port}`);
})

Hii i am new to learn express , i am trying to connect my mongodb to express js, i am not able to understand this error D:\Learn\Learn Express\ new_mongoose\node_modules\mongoose\lib\connection.js:792 err = new ServerSelectionError(); ^

MongooseServerSelectionError: connect ECONNREFUSED ::1:27017 at _handleConnectionErrors (D:\Learn\Learn Express\new_mongoose\node_modules\mongoose\lib\connection.js:792:11) at NativeConnection.openUri (D:\Learn\Learn Express\new_mongoose\node_modules\mongoose\lib\connection.js:767:11) at runNextTicks (node:internal/process/task_queues:60:5) at listOnTimeout (node:internal/timers:533:9) at process.processTimers (node:internal/timers:507: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: 656213806, lastWriteDate: 0, error: MongoNetworkError: connect ECONNREFUSED ::1:27017 at connectionFailureError (D:\Learn\Learn Express\new_mongoose\node_modules\mongodb\lib\cmap\connect.js:370:20) at Socket. (D:\Learn\Learn Express\new_mongoose\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 at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1487:16) { errno: -4078, code: 'ECONNREFUSED', syscall: 'connect', address: '::1', port: 27017 }, [Symbol(errorLabels)]: Set(1) { 'ResetPool' } }, 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 }

i was expecting connection successfull message at console,please help me

  • It looks mongoose is unable to establish the connection. Please make sure your mongodb is running and the port is `27017` – PRATHEESH PC May 22 '23 at 08:49
  • 1
    Does this answer your question? [Can't connect to MongoDB 6.0 Server locally using Nodejs driver](https://stackoverflow.com/questions/74609210/cant-connect-to-mongodb-6-0-server-locally-using-nodejs-driver) – Wernfried Domscheit May 22 '23 at 09:10
  • Please trim your code to make it easier to find your problem. Follow these guidelines to create a [minimal reproducible example](https://stackoverflow.com/help/minimal-reproducible-example). – Community May 23 '23 at 06:18

4 Answers4

1

In node.js v18, localhost uses ipv6 address (::1), and by default mongodb localhost doesn't have ipv6 enabled. That's why you're facing this issue.

If you want to use ipv4 localhost address (127.0.0.1),

  1. Either replace localhost with 127.0.0.1.
mongoose.connect("mongodb://127.0.0.1:27017/schooldb").then(() => {
    console.log("connection successfully ");
})
  1. OR use family: 4 parameter. This tells the node.js localhost to use ipv4 address.
mongoose.connect("mongodb://localhost:27017/schooldb",{
    family: 4,
}).then(() => {
    console.log("connection successfully ");
})

OR

If you want to use the ipv6 address, then just start mongod with --ipv6 as argument. This enables mongodb ipv6 address.

mongod --ipv6
PrathamJ
  • 162
  • 12
0

here mongodb trying to connect to the current system but it fails to connect because the database is not running on the current system to fix this use 0.0.0.0 instead of localhost.

mongoose.connect("mongodb://0.0.0.0:27017/schooldb").then(() => {
    console.log("connection successfully ");
})
sumanth
  • 318
  • 1
  • 6
  • 25
0

In my case, I simply replaced the connection string from 'mongodb://localhost/MyDBName' with 'mongodb://127.0.0.1:27017/MyDBName'. Also, please ensure that the MongoDB server is up and running.

enter image description here

saleem
  • 295
  • 2
  • 7
  • 15
0

In my case the issue was on mongodb access permission and here's how I solve it

Correct File Permissions

sudo chown -R mongodb:mongodb /var/lib/mongodb
sudo chmod -R 0755 /var/lib/mongodb
sudo chown -R mongodb:mongodb /var/log/mongodb
sudo chmod -R 0755 /var/log/mongodb

Remove Incorrect Ownership

sudo chown mongodb:mongodb /var/lib/mongodb/WiredTiger.turtle
sudo chown mongodb:mongodb /var/lib/mongodb/collection-0--9070219476800958121.wt

Start mongod

sudo systemctl start mongod

Check MongoDB Status

sudo systemctl status mongod