I am trying to connect to a Mongo app from my Node application using Mongoose. I have done this before on the same machine, but this time I am having a connection problem.
import { connect } from 'mongoose';
export class ConnectedModel {
protected async connect(): Promise<void>() {
const connectionString = 'mongodb://my-user-name:my-password@localhost/my-database';
await connect(connectionString);
}
}
This throws an error:
/my-project/node_modules/mongoose/lib/connection.js:807
const serverSelectionError = new ServerSelectionError();
^ MongooseServerSelectionError: connect ECONNREFUSED ::1:27017
at NativeConnection.Connection.openUri (/my-project/node_modules/mongoose/lib/connection.js:807:32)
// many lines of error stack
at UserModel.connect (/my-project/bin/www/models/connected.model.js:6:38)
I thought the problem must be something to do with my credentials but if I use mongo "mongodb://my-user-name:my-password@localhost/my-database"
from the command line it opens up the shell as the right user in the right database.
The user belongs to the database I am attempting to use, so I don’t think this is an authSource
problem and changing authSource has not had any effect so none of the solutions on this previous question are working for me.
Why does this connection string work from the command line but not through Mongoose? What do I need to change in order to be able to open the connection?
3
Answers
A bit weird but judging by this Mongoose issue it looks as though there's a problem with it trying to resolve
localhost
using IPV6 while Mongo is not running in IPV6 mode. Changing the ConnectionString tomongodb://my-user-name:[email protected]/my-database
has resolved the connection failure.The issue suggests checking
/etc/hosts
to ensure that127.0.0.1
is before::1
but on my system that is already the case, so this might be something to do with the environment on the Mac.You are getting
ECONNREFUSED
error, which basically means the PORT you are trying to use in order to connect is being used.Did you close the connection?
You can try to change the default PORT number and try to reconnect.
Find the Info here – Standard Connection String Format
TL;DR – Something like this
mongodb://[username:password@]host1[:port1][,...hostN[:portN]][/[defaultauthdb][?options]]
Run CMD as admin then
netstat -an
and look for PORT 27017Maybe you’re getting connect ECONNREFUSED error because you forgot to spin up MongoDB server.
After making sure you have MongoDB installed, open a new tab on your terminal and run the command:
Read: https://www.freecodecamp.org/news/learn-mongodb-a4ce205e7739/
Ref: https://www.mongodb.com/docs/manual/reference/program/mongod/#options