'Specifying a port in MongoDB URI does not allow me to connect to my local DB
I am testing a connection to a local DB using mongoose and mongodb. Whenever I specify a port when passing in the URI to mongoose.connect()
I get a connection refused error,
async function connectDB() {
const db = await mongoose.connect('mongodb://localhost:<PORT NR>/myCollection')
return db
}
However, the connection works whenever I do not specify a port number.
async function connectDB() {
const db = await mongoose.connect('mongodb://localhost/myCollection')
return db
}
Why is this the case? I have used the port numbers: 3000,3232,27017 and 3456. All of which to my knowledge are not in use.
Solution 1:[1]
If you are running mongo in default port then you can try to connect in below way
function connectMongoDB() {
let uri = "mongodb://localhost:27017/<db_name>?authSource=admin&ssl=false";
mongoose.connect(uri, { useUnifiedTopology: true, useNewUrlParser: true });
const connection = mongoose.connection;
connection.once("open", function() {
console.log("MongoDB database connection established successfully");
});
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Spoorthy |