How to Use Express.js With MongoDB for Full-Stack Apps

How to Use Express.js With MongoDB for Full-Stack Apps

Express.js is a powerful web application framework for Node.js that simplifies the process of building robust web applications and APIs. When combined with MongoDB, a NoSQL database, developers can create full-stack applications with ease. This article will guide you through the process of using Express.js with MongoDB for building full-stack apps.

Setting Up Your Environment

To get started, ensure you have Node.js and MongoDB installed on your machine. You can download Node.js from the official Node.js website and MongoDB from the MongoDB Community Download page.

Once you have them installed, create a new directory for your project and navigate into it:

mkdir my-fullstack-app
cd my-fullstack-app

Initialize a new Node.js project:

npm init -y

This command generates a package.json file, which keeps track of your project's dependencies.

Installing Required Packages

Next, install Express.js and Mongoose, which is an ODM (Object Data Modeling) library that simplifies interactions with MongoDB:

npm install express mongoose

Optionally, you can also install Nodemon, a tool that automatically restarts your server whenever you make changes to your files:

npm install --save-dev nodemon

Setting Up Express Server

Create a new file named server.js in your project directory:

touch server.js

Now, open server.js and set up a basic Express server:

const express = require('express');
const mongoose = require('mongoose');
const app = express();
const PORT = process.env.PORT || 5000;
app.use(express.json()); // To parse JSON bodies
app.listen(PORT, () => {
    console.log(`Server is running on http://localhost:${PORT}`);
});
// Connect to MongoDB
mongoose.connect('mongodb://localhost:27017/mydatabase', { 
    useNewUrlParser: true, 
    useUnifiedTopology: true 
}).then(() => {
    console.log('Connected to MongoDB');
}).catch(err => {
    console.error('MongoDB connection error:', err);
});

Creating a MongoDB Model

To interact with MongoDB, you need to create a schema and a model. Create a new directory called models and then create a file named User.js inside it:

mkdir models
touch models/User.js

Define the user schema in User.js:

const mongoose = require('mongoose');
const userSchema = new mongoose.Schema({
    name: {
        type: String,
        required: true
    },
    email: {
        type: String,
        required: true,
        unique: true
    },
    password: {
        type: String,
        required: true
    }
});
module.exports = mongoose.model('User', userSchema);

Setting Up Routes

Next, set up the routing for your API. Create a new directory called routes and create a file named userRoutes.js inside it:

mkdir routes
touch routes/userRoutes.js

Add some basic CRUD operations to userRoutes.js:

const express = require('express');
const User = require('../models/User');
const router = express.Router();
// Create a new user
router.post('/users', async (req, res) => {
    try {
        const newUser = new User(req.body);
        await newUser.save();
        res.status(201).send(newUser);
    } catch (error) {
        res.status(400).send(error);
    }
});
// Get all users
router.get('/users', async (req, res) => {
    try {
        const users = await User.find();
        res.status(200).send(users);
    } catch (error) {
        res.status(500).send(error);
    }
});
module.exports = router;

Integrating Routes in the Server

Now, integrate your routes into the main server file server.js:

const userRoutes = require('./routes/userRoutes');
app.use('/api', user