I am trying to connect and run Node.js server and connect to collection on MongoDB Atlas. Howewer, I am geting crash in line where I should get connection response. Please advise:
.env file:
MOVIEREVIEWS_DATABASE_URI=mongodb+srv://<user>:<password>@cluster0.wvtv6.mongodb.net/sample_mflix?retryWrites=true&w=majority
MOVIEREVIEWS_NS=sample_mflix
Index.js:
import express from 'express';
import cors from 'cors';
import MoviesRoute from './api/MoviesRoute.js';
import dotenv from 'dotenv';
import mongodb from 'mongodb';
class Index {
static app = express();
static router = express.Router();
static main() {
dotenv.config();
Index.setUpServer();
Index.setUpDatabase();
}
static setUpServer() {
Index.app.use(cors());
Index.app.use(express.json());
Index.app.use('/api/v1/movies',
MoviesRoute.configRoutes(Index.router));
Index.app.use('*', (req, res) => { res.status(404).json({ error: 'not found' }); });
}
static async setUpDatabase() {
const client = new mongodb.MongoClient(process.env.MOVIEREVIEWS_DB_URI);
const port = process.env.PORT || 8000;
try { // Connect to the MongoDB cluster
await client.connect();
Index.app.listen(port, () => {
console.log(`server is running on port:${port}`);
});
}
catch (e) {
console.error(e); process.exit(1); }
}
}
Index.main();
I cannot figure out what is missing :(