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
I use this to cover all error edge cases. Try it
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.
connectDB
module.mongoose.connect
function like so: