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