Express JS, EJS, mongoose project setup
Setting up a project for CRUD (Create, Read, Update, Delete) operations using Express.js, EJS, and Mongoose involves creating a web application where you can perform these operations on a MongoDB database. Below is a step-by-step guide to setting up such a project:
1. Set Up Your Project
Initialize the Project:
Create a new directory for your project and initialize it with npm:
mkdir express-crud-app cd express-crud-app npm init -y
Install Required Packages:
Install the necessary packages:
npm install express mongoose ejs body-parser
express
: Web framework for Node.js.mongoose
: MongoDB object modeling tool.ejs
: Templating engine for rendering views.body-parser
: Middleware for parsing request bodies (though with Express 4.16.0 and later, you can use built-inexpress.json()
andexpress.urlencoded()
).
2. Set Up Mongoose and Connect to MongoDB
Create the Application File:
Create a file named
app.js
in the root of your project:const express = require('express'); const mongoose = require('mongoose'); const path = require('path'); const bodyParser = require('body-parser'); const app = express(); // Connect to MongoDB mongoose.connect('mongodb://localhost:27017/crud-app', { useNewUrlParser: true, useUnifiedTopology: true }).then(() => { console.log('Connected to MongoDB'); }).catch(err => { console.error('Failed to connect to MongoDB', err); }); // Middleware app.use(bodyParser.urlencoded({ extended: true })); app.use(express.json()); // Set the view engine to EJS app.set('view engine', 'ejs'); app.set('views', path.join(__dirname, 'views')); // Routes will be defined here // Start the server app.listen(3000, () => { console.log('Server is running on http://localhost:3000'); });
3. Run and Test Your Application
Start the Server:
Run the application using:
node app.js
Access the Application:
Open your browser and navigate to
http://localhost:3000
to see the list of items and test CRUD operations.
Summary
- Set Up Project: Initialize the project and install dependencies.
- Connect to MongoDB: Use Mongoose to connect to your MongoDB database.
- Create Mongoose Model: Define a schema and model for your data.
- Define Routes: Implement CRUD routes to handle various operations.
- Create EJS Templates: Build views to display and manage data.
- Test Application: Run and verify the application functionality.