MongoDB connected...
Development server live on http://localhost:3000
node:internal/errors:465
ErrorCaptureStackTrace(err);
^
Error: querySrv ECONNREFUSED _mongodb._tcp.auctiondbcluster.s6rzg.mongodb.net
at QueryReqWrap.onresolve [as oncomplete] (node:dns:213:19) {
errno: undefined,
code: 'ECONNREFUSED',
syscall: 'querySrv',
hostname: '_mongodb._tcp.auctiondbcluster.s6rzg.mongodb.net'
}
Everything works smooth when I am connected to my wifi but when I am offline and starting the server it gives this error. And by the way no I am not trying to connect to MongoDB online cluster, I am trying to connect to local host (mongodb://localhost:27017/auctionDB).
Here the function I am using in app.js
const runServer = async () =>{
if(process.env.NODE_ENV !== "production"){
await connectDb(process.env.MONGODB_LOCAL_CONNECTION);
app.listen(PORT, ()=>{
console.log(`Development server live on http://localhost:${PORT}`);
})
} else {
await connectDb(process.env.MONGODB_CONNECTION_STRING);
app.listen(PORT, ()=>{
console.log(`Production server live on port ${PORT}`);
})
}
}
runServer();
In my .env
file NODE_ENV
is set to development.
Here is the connectDb.js
function I am using to connect to the database
const mongoose = require("mongoose");
/**
* @description: Connect to the database by providing the connection string.
* @param {String} uri | MongoDB URI
* @default: mongodb://localhost:27017/auctionDB
*
* @returns {undefined}
*/
const connectDb = (url = process.env.MONGODB_LOCAL_CONNECTION) => {
try {
const con = mongoose.connect(url, {
useNewUrlParser: true,
useUnifiedTopology: true
});
if(con) console.log("MongoDB connected...")
} catch(e){
console.log(`Error: ${e}`);
}
};
module.exports = connectDb;
Here is the entire project on github
2
Answers
You should
await
themongoose.connect
call, not the whole function:Make sure your MongoDB URL is [ mongodb://localhost:27017/ ], and not an online connection MongoDB URL.
At line 13