I am trying to connect to MongoDB Compass. I am using Typescript, Node.Js and Mongoose to connect however I am getting errors when trying to connect to it.
This is my mongo connection code
const url ='mongodb://localhost:27017/BlogApp';
mongoose.connect(url)
.then(() => {console.log("Connected to MongoDB")})
.catch((err) => console.log(err));
//*** BEEP BOOP ***//
app.listen(PORT, () => {
console.log(`Your server available at http://localhost:${PORT}`);
})
My server starts normally and operates normally, however the connection to MongoDB gives me this massive error and I have no idea whats wrong with it.
MongooseServerSelectionError: connect ECONNREFUSED ::1:27017
at NativeConnection.Connection.openUri (C:\Users\Filda\Desktop\Node.Js\InstaClone\backend\node_modules\mongoose\lib\connection.js:819:32)
at C:\Users\Filda\Desktop\Node.Js\InstaClone\backend\node_modules\mongoose\lib\index.js:377:10
at C:\Users\Filda\Desktop\Node.Js\InstaClone\backend\node_modules\mongoose\lib\helpers\promiseOrCallback.js:32:5
at new Promise (<anonymous>)
at promiseOrCallback (C:\Users\Filda\Desktop\Node.Js\InstaClone\backend\node_modules\mongoose\lib\helpers\promiseOrCallback.js:31:10)
at Mongoose._promiseOrCallback (C:\Users\Filda\Desktop\Node.Js\InstaClone\backend\node_modules\mongoose\lib\index.js:1220:10)
at Mongoose.connect (C:\Users\Filda\Desktop\Node.Js\InstaClone\backend\node_modules\mongoose\lib\index.js:376:20)
at Object.<anonymous> (C:\Users\Filda\Desktop\Node.Js\InstaClone\backend\index.ts:31:10)
at Module._compile (node:internal/modules/cjs/loader:1112:14)
at Module.m._compile (C:\Users\Filda\Desktop\Node.Js\InstaClone\backend\node_modules\ts-node\src\index.ts:1597:23) {
reason: TopologyDescription {
type: 'Unknown',
servers: Map(1) { 'localhost:27017' => [ServerDescription] },
stale: false,
compatible: true,
heartbeatFrequencyMS: 10000,
localThresholdMS: 15,
logicalSessionTimeoutMinutes: undefined
},
code
I am using the same setup as on my other projects (I just coppied the code), but this time it doesn't connect. My older projects use the same backend setup, this time I only rewrote it for typescript.
CodePudding user response:
I don't know which verison of mongoose or mongoDB you are using, but you need to tell mongoose how to "look" for a connection so your code should look like this. I am not really sure how exactly it works, but you need to tell mongoose to look with IPv4 not IPv6 (Don't know why exactly)
const url = 'mongodb://localhost:27017/BlogApp';
const options = {
useNewUrlParser: true,
useUnifiedTopology: true,
family: 4 // Use IPv4, skip trying IPv6
}
mongoose.Promise = global.Promise;
mongoose.connect(url!, options)
.then(() => {console.log("Connected to MongoDB")})
.catch((err) => console.log(err));
//*** BEEP BOOP ***//
app.listen(PORT, () => {
console.log(`Your server available at http://localhost:${PORT}`);
})