0

I'm trying to connect to MongoDB using mongoose but it is not working.

Here's my sample code to connect to it.

const express = require("express");

const app = express();


const mongoose = require('mongoose');

//connecting to MongoDB using mongoose
mongoose.connect('mongodb://localhost:27017/testdb').then(() => {
console.log("Connected to Database");
}).catch((err) => {
    console.log("Not Connected to Database ERROR! ", err);
});

app.get("/", function(req, res){
    res.send("Everything is running properly!");
});

app.listen(3000, function(){
    console.log("Server succesfully started on port 3000!");
});

Before doing nodemon app.js, I typed mongod in another tab so that MongoDB is started running. It gave waiting for connections on port 27017 so it means MongoDB is running.

Now here comes the error, when I give command nodemon app.js

[nodemon] starting `node app.js`
Server succesfully started on port 3000!
Not Connected to Database ERROR!  MongooseServerSelectionError: connect ECONNREFUSED ::1:27017
    at NativeConnection.Connection.openUri (F:\Web Projects\Image_Site\node_modules\mongoose\lib\connection.js:797:32)
    at F:\Web Projects\Image_Site\node_modules\mongoose\lib\index.js:332:10
    at F:\Web Projects\Image_Site\node_modules\mongoose\lib\helpers\promiseOrCallback.js:32:5
    at new Promise (<anonymous>)
    at promiseOrCallback (F:\Web Projects\Image_Site\node_modules\mongoose\lib\helpers\promiseOrCallback.js:31:10)
    at Mongoose._promiseOrCallback (F:\Web Projects\Image_Site\node_modules\mongoose\lib\index.js:1153:10)
    at Mongoose.connect (F:\Web Projects\Image_Site\node_modules\mongoose\lib\index.js:331:20)
    at Object.<anonymous> (F:\Web Projects\Image_Site\app.js:13:10)
    at Module._compile (node:internal/modules/cjs/loader:1095:14)
    at Object.Module._extensions..js (node:internal/modules/cjs/loader:1147:10) {
  reason: TopologyDescription {
    type: 'Unknown',
    servers: Map(1) { 'localhost:27017' => [ServerDescription] },
    stale: false,
    compatible: true,
    heartbeatFrequencyMS: 10000,
    localThresholdMS: 15,
    logicalSessionTimeoutMinutes: undefined
  }
}

2 Answers2

1

Finally, It is solved. It was solved by enabling Ipv6 by mongod --ipv6

Thanks to an answer found on StackOverflow. https://stackoverflow.com/a/69857909/16967940

0

It seems that you don't have the database testdb .

  • If not exist then it will create a new database with that name. Anyways it is fixed by running MongoDB as mongod --ipv6 , I don't know why I need to write --ipv6 explicitly because in my old PC I never faced this issue. – Venkat Lohith Dasari Nov 17 '21 at 08:58