DEV Community

Pranav Bakare
Pranav Bakare

Posted on

MERN stack application with a MongoDB connection using ES6 syntax

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
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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}`);
});
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

You should see the output:

MongoDB connected successfully!
Server is running on port 5000
Enter fullscreen mode Exit fullscreen mode

ES6 Syntax Breakdown:

  1. import/export: ES6 uses import for loading modules, replacing require().
  2. Arrow functions (=>): The connectDB function uses an arrow function for cleaner syntax.
  3. Async/Await: The connectDB function uses async/await for handling asynchronous code more cleanly compared to promises.
  4. Template literals: Backticks (`) are used in console.log for dynamic port logging.

This setup will ensure your MERN stack application connects to MongoDB using modern JavaScript practices.

Top comments (0)