skip to Main Content

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


  1. The issue could be related to the absence of the await keyword, try:

    import mongoose from 'mongoose';
    
    await mongoose
      .connect(config.mongo.url)
      .then(() => {
        console.log('Connected successfully to MongoDB');
        startServer();
      })
      .catch((e: Error) => {
        console.log('Erorr while connecting to MongoDB: ' + e);
      });
    

    I would also suggest loading your connection string as an environment variable through a zero-dependency module such as dotenv.

    Login or Signup to reply.
  2. 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"
    };
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search