Back End Development and APIs Projects - Exercise Tracker

Tell us what’s happening:

I don’t know what is wrong with my code. I asked someone to look at it, and they said nothing is wrong with my code, especially the part to connect to MongoDB Atlas. I have tried all kinds of methods to solve it but none of them work. This is my error: Failed to connect to MongoDB Error: querySrv ENOTFOUND _mongodb._tcp.cluster0.mongodb.net
at QueryReqWrap.onresolve [as oncomplete] (node:internal/dns/promises:293:17) {
errno: undefined,
code: ‘ENOTFOUND’,
syscall: ‘querySrv’,
hostn

Your code so far

const express = require(‘express’);
const app = express();
const cors = require(‘cors’);
require(‘dotenv’).config();
const mongoose = require(‘mongoose’);

const connectToDatabase = async () => {
try {
mongoose.set(‘strictQuery’, false);
await mongoose.connect(process.env.MONGO_URI);
console.log(‘Connected to DB successfully’);
} catch (err) {
console.error(‘Failed to connect to MongoDB’, err);
process.exit(1); // Exit the process with failure
}
};

connectToDatabase();

const userSchema = new mongoose.Schema({
username: {
type: String,
unique: true,
},
});

const User = mongoose.model(‘User’, userSchema);

app.use(cors());
app.use(express.urlencoded({ extended: true }));
app.use(express.static(‘public’));
app.get(‘/’, (req, res) => {
res.sendFile(__dirname + ‘/views/index.html’);
});

// POST to /api/users username
app.post(‘/api/users’, async (req, res) => {
try {
const username = req.body.username;

const user = await User.create({ username });
res.json(user);

} catch (error) {
res.status(400).json({ error: error.message });
}
});

const listener = app.listen(process.env.PORT || 3001, () => {
console.log('Your app is listening on port ’ + listener.address().port);
});

Challenge Information:

Back End Development and APIs Projects - Exercise Tracker