Site icon MageComp Blog

Building a CRUD Application with Node.js and MongoDB

In Node.js, databases are used to store and retrieve data for web applications. They are an essential part of building dynamic and scalable applications. Node.js provides various modules and packages to work with databases such as MySQL, PostgreSQL, MongoDB, and more. They allow developers to store, query, and manipulate data using various operations such as create, read, update, and delete (CRUD).

They are particularly useful in web applications where data needs to be stored and retrieved quickly and efficiently.

In addition to storing data, databases also provide features such as data indexing, data integrity, and data security. These features ensure that data is stored and accessed correctly and securely.

Hence they are a critical component of web application development in Node.js, and developers must have a good understanding of how to work with databases and how to use them efficiently to build robust applications.

Databases and ORMs

Databases and ORMs (Object Relational Mappers) play a vital role in building web applications using Node.js. As described, a database is a collection of data that is organised in a specific manner to enable easy access, management, and updating of information. In a Node.js application, databases are used to store and retrieve data.

Using Mongoose

As described above, ORMs (Object-Relational Mapping) are used to simplify the process of interacting with databases, making it easier to perform CRUD (Create, Read, Update, Delete) operations by using object-oriented programming concepts rather than directly writing SQL queries. With ORMs, developers can work with data in a more intuitive and efficient way, increasing productivity and reducing errors.

Prerequisites

Before we dive into the coding part, ensure you have the following installed on your computer:

Steps to Build CRUD Application with Node.js and MongoDB

Initialize Node.js Project

npm init -y
npm install express mongoose body-parser

Set Up MongoDB

Make sure MongoDB is installed and running locally or use a cloud-based MongoDB service like MongoDB Atlas.

Project Structure

Create the following structure for your project:

index.js

const express = require('express');
const bodyParser = require('body-parser');
const mongoose = require('mongoose');
const blogRoutes = require('./routes/blogRoutes');
const app = express();
const PORT = process.env.PORT || 3000;
app.use(bodyParser.json());
// Connect to MongoDB
mongoose.connect('mongodb://localhost:27017/blogDB', {
    useNewUrlParser: true,
    useUnifiedTopology: true
});
const db = mongoose.connection;
db.on('error', console.error.bind(console, 'MongoDB connection error:'));
db.once('open', function () {
    console.log('Connected to MongoDB');
});
// Routes
app.use('/blogs', blogRoutes);
app.listen(PORT, () => {
    console.log(`Server is running on http://localhost:${PORT}`);
});

models/blogModel.js

const mongoose = require('mongoose');
const blogSchema = new mongoose.Schema({
    title: String,
    content: String,
    author: String
});
module.exports = mongoose.model('Blog', blogSchema);

controllers/blogController.js

const Blog = require('../models/blogModel');
// Controller functions
exports.getAllBlogs = async (req, res) => {
    try {
        const blogs = await Blog.find();
        res.json(blogs);
    } catch (err) {
        res.status(500).json({ message: err.message });
    }
};
exports.getBlogById = async (req, res) => {
    try {
        const blog = await Blog.findById(req.params.id);
        if (!blog) {
            return res.status(404).json({ message: 'Blog not found' });
        }
        res.json(blog);
    } catch (err) {
        res.status(500).json({ message: err.message });
    }
};
exports.createBlog = async (req, res) => {
    const blog = new Blog({
        title: req.body.title,
        content: req.body.content,
        author: req.body.author
    });
    try {
        const newBlog = await blog.save();
        res.status(201).json(newBlog);
    } catch (err) {
        res.status(400).json({ message: err.message });
    }
};
exports.updateBlog = async (req, res) => {
    try {
        const updatedBlog = await Blog.findByIdAndUpdate(req.params.id, req.body, { new:
            true });
        res.json(updatedBlog);
    } catch (err) {
        res.status(400).json({ message: err.message });
    }
};
exports.deleteBlog = async (req, res) => {
    try {
        await Blog.findByIdAndDelete(req.params.id);
        res.json({ message: 'Deleted blog' });
    } catch (err) {
        res.status(500).json({ message: err.message });
    }
};

routes/blogRoutes.js

const express = require('express');
const router = express.Router();
const blogController = require('../controllers/blogController');

router.get('/', blogController.getAllBlogs);
router.post('/', blogController.createBlog);
router.get('/:id', blogController.getBlogById);
router.patch('/:id', blogController.updateBlog);
router.delete('/:id', blogController.deleteBlog);

module.exports = router;

Conclusion

You’ve now created a basic CRUD application using Node.js and MongoDB! This setup serves as a foundation for building more complex web applications. Experiment with expanding this application by adding more features, such as user authentication or more complex data relationships.

Remember, the key to mastering web development is practice and continuous learning. Keep experimenting with different aspects of Node.js and MongoDB, and you’ll become proficient in building back-end services for your applications.

Exit mobile version