iam strugling to connect my simple server to mongodb using atlas. i have created a new project and database with cluster, they provide a connect string i use exactly like they say. but i get this error after sometime. here is my code
import mongoose from "mongoose";
mongoose
.connect(
"mongodb+srv://carproject:[email protected]/?retryWrites=true&w=majority&appName=car-project"
)
.then(() => {
console.log("connected");
}).catch(err=>
{
console.log(err)
}
)
const app = express();
app.get("/", (req, res) => {
res.send("Hello, World!!!");
});
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`);
});
```` and i get this error in the console after few minutes `Error: queryTxt ETIMEOUT car-project.u4g8sog.mongodb.net
at QueryReqWrap.onresolve [as oncomplete] (node:internal/dns/promises:251:17) {
errno: undefined,
code: 'ETIMEOUT',
syscall: 'queryTxt',
hostname: 'car-project.u4g8sog.mongodb.net'
}````
2
Answers
The issue could be related to the absence of the
await
keyword, try:I would also suggest loading your connection string as an environment variable through a zero-dependency module such as dotenv.
You can try with this:
And the db config db.config.js file: