skip to Main Content

So I Put a try catch system that is checking if I can connect to my MongoDB an if it doesn’t don’t run the server.

When it does connect all well and good, when I try and check the error system (just console.log(‘error’)).
I changed my password and it doesn’t return ‘error’ and just runs the server.

General code mockup:

const express = require('express')
const app = express()
const tasks = require('./routes/tasks')
const connectDB = require('./db/connect')


// middleware
app.use(express.json())

// routes
app.get('/hello', (req, res) => {
  res.send('<h2>i know how to do things</h2>')
})

app.post('/api/v1/tasks', tasks)
app.use('/api/v1/tasks', tasks)

const port = 3000;
const start = async () => {

try {
    await connectDB
    app.listen(port, console.log(`server is listening on port ${port}`))
} catch (error) {
    console.log('error')
}

}

start()

this is the code for the connectDB pull

const mongoose = require('mongoose')

const connectionString = "mongodb+srv://user:[email protected]/TASK-MANAGER?retryWrites=true&w=majority&appName=Cluster0"

const connectDB = (url) => {
    return mongoose.connect(connectionString, {
        useNewUrlParser: true,
        useCreateIndex: true,
        useFindAndModify: false,
        useUnifiedTopology: true,
    })
}

module.exports = connectDB

I’ve rewritten the code 3 times and I cannot get it working, I’m following "Node.js/Express Course – Build 4 Projects" on YouTube

2

Answers


  1. I use this to cover all error edge cases. Try it

    const connectDB = async () => {
      try {
        const res = await mongoose.connect(connectionString, {
          useNewUrlParser: true,
          useCreateIndex: true,
          useFindAndModify: false,
          useUnifiedTopology: true,
        });
        if(!res) return console.log('Error connecting to MongoDB');
        console.log('Connected to MongoDB');
      } catch (error) {
        console.error('Error connecting to MongoDB:', error.message);
        throw new Error('Unable to connect to MongoDB');
      }
    };
    
    Login or Signup to reply.
  2. Connecting to mongodb with mongoose is a very simple process. As a beginner you want to focus on getting things up and running, making queries and progress with your learning. Stick to the basics before abstracting things away into reusable modules.

    1. Delete all of this:
    const start = async () => {
       try {
          await connectDB
          app.listen(port, console.log(`server is listening on port ${port}`))
       } catch (error) {
          console.log('error')
       }
    }
    start()
    
    1. Delete the entire connectDB module.
    2. Update your app.js file to use the mongoose.connect function like so:
    const mongoose = require('mongoose');
    const express = require('express');
    const app = express();
    const tasks = require('./routes/tasks');
    const connectionString = "mongodb+srv://user:[email protected]/TASK-MANAGER?retryWrites=true&w=majority&appName=Cluster0";
    
    // middleware
    app.use(express.json());
    
    // routes
    app.get('/hello', (req, res) => {
      res.send('<h2>i know how to do things</h2>')
    });
    
    app.post('/api/v1/tasks', tasks);
    app.use('/api/v1/tasks', tasks);
    
    const port = 3000;
    mongoose.connect(connectionString).then(()=>{
       console.log('Connected to mongodb');
    }).catch(err =>{
       console.log('Error Connecting', err);
    });
    
    app.listen(port, () => {
        console.log(`Server listening on port ${port}`);
    });
    
    1. Try to find a more up-to-date tutorial.
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search