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!
Before we begin, ensure you have the following installed:
Additionally, if you aren't familiar with TypeScript, a basic understanding will help you grasp our code examples more efficiently.
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:
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.
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
.
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.
We are now ready to implement the core CRUD functionalities.
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 }); } });
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 }); } });
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 }); } });
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 }); } });
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 itemGET /items
: To get all itemsGET /items/:id
: To get a specific itemPUT /items/:id
: To update an itemDELETE /items/:id
: To delete an itemBy 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!
14/10/2024 | NodeJS
08/10/2024 | NodeJS
31/08/2024 | NodeJS
14/10/2024 | NodeJS
23/07/2024 | NodeJS
14/10/2024 | NodeJS
14/10/2024 | NodeJS
14/10/2024 | NodeJS
23/07/2024 | NodeJS
18/09/2024 | NodeJS