logologo
  • AI Tools

    DB Query GeneratorMock InterviewResume BuilderLearning Path GeneratorCheatsheet GeneratorAgentic Prompt GeneratorCompany ResearchCover Letter Generator
  • XpertoAI
  • MVP Ready
  • Resources

    CertificationsTopicsExpertsCollectionsArticlesQuestionsVideosJobs
logologo

Elevate Your Coding with our comprehensive articles and niche collections.

Useful Links

  • Contact Us
  • Privacy Policy
  • Terms & Conditions
  • Refund & Cancellation
  • About Us

Resources

  • Xperto-AI
  • Certifications
  • Python
  • GenAI
  • Machine Learning

Interviews

  • DSA
  • System Design
  • Design Patterns
  • Frontend System Design
  • ReactJS

Procodebase © 2024. All rights reserved.

Level Up Your Skills with Xperto-AI

A multi-AI agent platform that helps you level up your development skills and ace your interview preparation to secure your dream job.

Launch Xperto-AI

Implementing CRUD Operations in Node.js with MongoDB and TypeScript

author
Generated by
Abhishek Goyan

14/10/2024

Node.js

Sign in to read full article

Building a CRUD application is one of the foundational exercises in web development. This guide will walk you through the process of implementing Create, Read, Update, and Delete operations using Node.js, MongoDB, and TypeScript. If you're ready to dive into the world of full-stack JavaScript, let's get started!

Prerequisites

Before we begin, ensure you have the following installed:

  • Node.js
  • npm (Node Package Manager)
  • MongoDB
  • TypeScript

Additionally, if you aren't familiar with TypeScript, a basic understanding will help you grasp our code examples more efficiently.

Setting Up Your Project

First, create a new directory for your project and initialize it with npm.

mkdir crud-app cd crud-app npm init -y

Next, install the necessary packages:

npm install express mongoose body-parser typescript @types/node @types/express ts-node --save

Here’s a breakdown of what we just installed:

  • express: A web framework for Node.js to handle routing.
  • mongoose: An ODM (Object Data Modeling) library for MongoDB and Node.js.
  • body-parser: Middleware to parse incoming request bodies.
  • typescript: A superset of JavaScript that adds type definitions.
  • @types/: Type definitions for TypeScript for node and express.
  • ts-node: A TypeScript execution environment for Node.js.

Now, create a tsconfig.json file to configure TypeScript in your project.

{ "compilerOptions": { "target": "ES6", "module": "commonjs", "strict": true, "esModuleInterop": true, "skipLibCheck": true, "forceConsistentCasingInFileNames": true }, "include": ["src/**/*.ts"], "exclude": ["node_modules"] }

This configuration file specifies how TypeScript will compile your app, with a focus on ES6 compatibility.

Setting Up Your Server

Let’s create a simple server using Express. In the root directory, create a folder called src and inside it, create a file named server.ts.

import express from 'express'; import mongoose from 'mongoose'; import bodyParser from 'body-parser'; const app = express(); const port = 3000; // Middleware app.use(bodyParser.json()); // Connect to MongoDB mongoose.connect('mongodb://localhost:27017/crud-app', { useNewUrlParser: true, useUnifiedTopology: true }); // Start server app.listen(port, () => { console.log(`Server is running on http://localhost:${port}`); });

In this code, we set up our Express server and connect to a MongoDB database named crud-app.

Defining the Data Model

Next, we need to create a data model using Mongoose. In the src directory, create a folder called models and a file named item.ts.

import mongoose, { Document, Schema } from 'mongoose'; export interface Item extends Document { title: string; description: string; } const itemSchema: Schema = new Schema({ title: { type: String, required: true }, description: { type: String, required: true }, }); export const ItemModel = mongoose.model<Item>('Item', itemSchema);

Here, we define an Item interface and a corresponding Mongoose schema that enforces the structure of our items in the database.

Implementing CRUD Operations

We are now ready to implement the core CRUD functionalities.

Create Operation

Add the following route to your server.ts file to create a new item:

app.post('/items', async (req, res) => { const newItem = new ItemModel(req.body); try { const savedItem = await newItem.save(); res.status(201).json(savedItem); } catch (error) { res.status(500).json({ message: error.message }); } });

Read Operation

To fetch all items, you can add this route:

app.get('/items', async (req, res) => { try { const items = await ItemModel.find(); res.status(200).json(items); } catch (error) { res.status(500).json({ message: error.message }); } });

If you want to retrieve a single item by ID, use this route:

app.get('/items/:id', async (req, res) => { try { const item = await ItemModel.findById(req.params.id); if (!item) return res.status(404).json({ message: 'Item not found' }); res.status(200).json(item); } catch (error) { res.status(500).json({ message: error.message }); } });

Update Operation

To update an existing item, add the following code:

app.put('/items/:id', async (req, res) => { try { const updatedItem = await ItemModel.findByIdAndUpdate(req.params.id, req.body, { new: true }); if (!updatedItem) return res.status(404).json({ message: 'Item not found' }); res.status(200).json(updatedItem); } catch (error) { res.status(500).json({ message: error.message }); } });

Delete Operation

Finally, implement the delete functionality:

app.delete('/items/:id', async (req, res) => { try { const deletedItem = await ItemModel.findByIdAndDelete(req.params.id); if (!deletedItem) return res.status(404).json({ message: 'Item not found' }); res.status(204).send(); } catch (error) { res.status(500).json({ message: error.message }); } });

Running the Application

You can run your application using:

npx ts-node src/server.ts

Once the application is up and running, you can use a tool like Postman to test your CRUD operations. Be sure to check the endpoints:

  • POST /items: To create a new item
  • GET /items: To get all items
  • GET /items/:id: To get a specific item
  • PUT /items/:id: To update an item
  • DELETE /items/:id: To delete an item

By following this guide, you've successfully built a CRUD application that lets you manipulate data in a MongoDB database using Node.js and TypeScript. Feel free to enhance your application with validation, authentication, and error handling as you continue your development journey!

Popular Tags

Node.jsMongoDBTypeScript

Share now!

Like & Bookmark!

Related Collections

  • Node.js Mastery: From Foundations to Frontiers

    08/10/2024 | NodeJS

  • Build a CRUD App with Node.js, MongoDB, and TypeScript

    14/10/2024 | NodeJS

  • Optimising Backend APIs - Node.js

    31/08/2024 | NodeJS

Related Articles

  • Testing CRUD Operations in Your Node.js Application

    14/10/2024 | NodeJS

  • Setting Up Your Development Environment for Node.js

    14/10/2024 | NodeJS

  • Implementing RabbitMQ with Node.js

    18/09/2024 | NodeJS

  • Implementing CRUD Operations in Node.js with MongoDB and TypeScript

    14/10/2024 | NodeJS

  • Introduction to Node.js, MongoDB, and TypeScript

    14/10/2024 | NodeJS

  • Load testing with Node.js for Scalable Backend Architecture

    23/07/2024 | NodeJS

  • Connecting to MongoDB with Mongoose

    14/10/2024 | NodeJS

Popular Category

  • Python
  • Generative AI
  • Machine Learning
  • ReactJS
  • System Design