strugling to connect express app to mongodb atlas

28 views Asked by At

I am struggling to connect my simple server to MongoDB using Atlas. I have created a new project and database with cluster. They provide a connect string that I use exactly like they say, but I get this error after sometime.

Here is my code:

import express from "express";
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}`);
});

I get this error in the console after a 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'
}
1

There are 1 answers

0
David G. On

You can try with this:

const mongoose = require("mongoose");
const dbConfig = require("./config/db.config");

mongoose
.connect(`mongodb+srv://${dbConfig.USER}:${dbConfig.PASSWORD}@${dbConfig.CLUSTER}/${dbConfig.DB}?retryWrites=true&w=majority`, {
    useNewUrlParser: true,
    useUnifiedTopology: true
  })
  .then(() => {
    console.log("-> [ OK ] Connected.");
    boot.initial();
  }) 
  .catch(err => {
    console.error("-> [ FAIL ] Not connected.", err);
    process.exit();
  });

And the db config db.config.js file:

module.exports = {
    CLUSTER: "your-cluster",
    PORT: your-port,
    USER: "your-user,
    PASSWORD: "your-password",
    DB: "your-db"
};