Here’s how to set up a MERN stack application with a MongoDB connection using ES6 syntax:
Step 1: Get the MongoDB URI
You'll get a MongoDB URI during setup if you're using MongoDB Atlas:
mongodb+srv://<username>:<password>@cluster0.mongodb.net/<database>?retryWrites=true&w=majority
Replace:
-
<username>
with your MongoDB username. -
<password>
with your MongoDB password. -
<database>
with your database name.
Step 2: Install Mongoose in the Backend
Run the following command to install Mongoose:
npm install mongoose
Step 3: Create a .env
File
Create a .env
file to store your MongoDB URI securely:
MONGO_URI=mongodb+srv://<username>:<password>@cluster0.mongodb.net/<database>?retryWrites=true&w=majority
Step 4: Connect to MongoDB in server.js
or app.js
(ES6 Syntax)
// Import dependencies
import express from 'express';
import mongoose from 'mongoose';
import dotenv from 'dotenv';
// Initialize dotenv
dotenv.config();
// Initialize Express app
const app = express();
// Middleware
app.use(express.json());
// Connect to MongoDB using ES6 promises
const connectDB = async () => {
try {
await mongoose.connect(process.env.MONGO_URI, {
useNewUrlParser: true,
useUnifiedTopology: true,
});
console.log('MongoDB connected successfully!');
} catch (err) {
console.error('MongoDB connection error:', err);
process.exit(1); // Exit process with failure
}
};
// Call the MongoDB connection function
connectDB();
// Example route
app.get('/', (req, res) => {
res.send('MERN Stack Application with ES6 Syntax');
});
// Start the server
const PORT = process.env.PORT || 5000;
app.listen(PORT, () => {
console.log(`Server running on port ${PORT}`);
});
Step 5: Set Up Your Express Server (Optional)
This is already included above.
Step 6: Test Your Connection
Start the server using:
node server.js
You should see the output:
MongoDB connected successfully!
Server is running on port 5000
ES6 Syntax Breakdown:
-
import
/export
: ES6 usesimport
for loading modules, replacingrequire()
. -
Arrow functions (
=>
): TheconnectDB
function uses an arrow function for cleaner syntax. -
Async/Await: The
connectDB
function usesasync/await
for handling asynchronous code more cleanly compared to promises. -
Template literals: Backticks (
`
) are used inconsole.log
for dynamic port logging.
This setup will ensure your MERN stack application connects to MongoDB using modern JavaScript practices.
Top comments (0)