How to connect a database with EJS in a Node.js Express app

To integrate a database with EJS in a Node.js Express application, you’ll need to go through a few fundamental steps. Below is a detailed guide that will help you set up your environment and successfully connect a database to your Node.js Express application, while using EJS for rendering views.

Step 1: Set Up the Express Application

Start by creating a new directory for your project and initializing it with npm:

bash
mkdir myapp
cd myapp
npm init -y

Install the required dependencies:

bash
npm install express ejs

Step 2: Choose and Install a Database

For simplicity, let’s assume you are using a MongoDB database with Mongoose as the ODM (Object Data Modeling) library. Install mongoose:

bash
npm install mongoose

If you’re using another database like MySQL or PostgreSQL, you’d install corresponding packages like mysql2 or pg.

Step 3: Create the Basic App Structure

Create an Express application with EJS as the view engine:

javascript
// app.js
const express = require(‘express’);
const mongoose = require(‘mongoose’);
const app = express();

// Set ‘views’ directory and ‘ejs’ as the view engine
app.set(‘views’, ‘./views’);
app.set(‘view engine’, ‘ejs’);

// Connect to MongoDB
mongoose.connect(‘mongodb://localhost:27017/mydatabase’, {
useNewUrlParser: true,
useUnifiedTopology: true,
});

// Define a basic route
app.get(‘/’, (req, res) => {
res.render(‘index’, { title: ‘My App’, message: ‘Hello, World!’ });
});

// Start the server
app.listen(3000, () => {
console.log(‘Server is running on http://localhost:3000’);
});

Step 4: Create a Mongoose Model

Say you want to add a model for storing users:

javascript
// models/User.js
const mongoose = require(‘mongoose’);

const userSchema = new mongoose.Schema({
name: String,
email: String,
});

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

module.exports = User;

Step 5: Interact with the Database and Render Data

Create a route that interacts with your database:

javascript
// Continue in app.js or create a new routes file

const User = require(‘./models/User’);

// Define a route that fetches users from the database
app.get(‘/users’, async (req, res) => {
const users = await User.find();
res.render(‘users’, { title: ‘User List’, users: users });
});

Step 6: Create EJS Templates

Create EJS templates in the views directory.

views/index.ejs

html




<%= title %>

<%= message %>


views/users.ejs

html




<%= title %>

User List

    <% users.forEach(user => { %>

  • <%= user.name %> (<%= user.email %>)
  • <% }) %>


Step 7: Test Your Application

Run your application using Node.js:

bash
node app.js

Visit http://localhost:3000/ to see the EJS rendered homepage, and http://localhost:3000/users to see the list of users fetched from the database.

Conclusion

By following these steps, you set up an Express application using EJS for views and connected it to a MongoDB database using Mongoose. For other databases, such as MySQL or PostgreSQL, you would replace Mongoose with the relevant database driver or ORM, and the query methods would differ accordingly.


One response to “How to connect a database with EJS in a Node.js Express app”

  1. This is a well-structured and useful guide for beginners looking to connect a MongoDB database with EJS in a Node.js Express app. I’d like to add a few additional considerations that can enhance the functionality and stability of your application:

    1. **Error Handling**: Implementing error handling for database connections and API requests is crucial. It would be beneficial to add try-catch blocks in your asynchronous route handlers. This way, if there is an issue with fetching users, you can display an appropriate message to the user rather than leaving them with a blank screen.

    Example:
    “`javascript
    app.get(‘/users’, async (req, res) => {
    try {
    const users = await User.find();
    res.render(‘users’, { title: ‘User List’, users: users });
    } catch (error) {
    console.error(error);
    res.status(500).send(‘Error retrieving users’);
    }
    });
    “`

    2. **Input Validation and Sanitization**: If you’re planning on extending this app with forms for adding or updating users, consider integrating libraries such as `express-validator` to validate and sanitize user input. This is essential for avoiding common security issues like NoSQL injection attacks.

    3. **Environment Variables**: Instead of hardcoding your database connection string in the application code, it’s a good practice to use environment variables. Utilizing packages like `dotenv` can help keep sensitive information secure and make your code cleaner.

    Example:
    “`

Leave a Reply to Hubsadmin Cancel reply

Your email address will not be published. Required fields are marked *