Building a TODO List Backend with Node.js, Express, MongoDB, and TypeScript
Certainly! Below is a simple example of a TODO list backend using Node.js, Express, MongoDB, and TypeScript. Before you start, make sure you have Node.js, npm, and MongoDB installed on your machine.
- Create a new project folder and initialize it:
mkdir todo-backend
cd todo-backend
npm init -y
- Install the necessary dependencies:
npm install express mongoose body-parser typescript ts-node @types/node @types/express @types/mongoose
- Create a
tsconfig.json
file in the project root:
{
"compilerOptions": {
"target": "es6",
"module": "commonjs",
"outDir": "./dist",
"rootDir": "./src",
"strict": true
}
}
- Create a
src
folder and add aserver.ts
file inside it:
// src/server.ts
import express from 'express';
import mongoose from 'mongoose';
import bodyParser from 'body-parser';
import { TodoRoutes } from './routes/todo.routes';
class App {
public app: express.Application;
public mongoUrl: string = 'mongodb://localhost:27017/todo';
constructor() {
this.app = express();
this.config();
this.mongoSetup();
this.routes();
}
private config(): void {
this.app.use(bodyParser.json());
this.app.use(bodyParser.urlencoded({ extended: false }));
}
private mongoSetup(): void {
mongoose.Promise = global.Promise;
mongoose.connect(this.mongoUrl, { useNewUrlParser: true, useUnifiedTopology: true });
}
private routes(): void {
const router = express.Router();
this.app.use('/api', new TodoRoutes().getRoutes());
}
}
const PORT = 3000;
const app = new App().app;
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`);
});
- Create a
src/models/todo.model.ts
file:
// src/models/todo.model.ts
import mongoose, { Schema, Document } from 'mongoose';
export interface ITodo extends Document {
text: string;
completed: boolean;
}
const TodoSchema: Schema = new Schema({
text: { type: String, required: true },
completed: { type: Boolean, default: false },
});
export default mongoose.model<ITodo>('Todo', TodoSchema);
- Create a
src/routes/todo.routes.ts
file:
// src/routes/todo.routes.ts
import express, { Router } from 'express';
import TodoController from '../controllers/todo.controller';
export class TodoRoutes {
private router: Router = express.Router();
private todoController: TodoController = new TodoController();
constructor() {
this.config();
}
private config(): void {
this.router.post('/todos', this.todoController.createTodo);
this.router.get('/todos', this.todoController.getTodos);
this.router.get('/todos/:id', this.todoController.getTodoById);
this.router.put('/todos/:id', this.todoController.updateTodo);
this.router.delete('/todos/:id', this.todoController.deleteTodo);
}
public getRoutes(): Router {
return this.router;
}
}
- Create a
src/controllers/todo.controller.ts
file:
// src/controllers/todo.controller.ts
import { Request, Response } from 'express';
import Todo from '../models/todo.model';
export default class TodoController {
public createTodo(req: Request, res: Response): void {
const newTodo = new Todo(req.body);
newTodo.save((err, todo) => {
if (err) {
res.status(400).json(err);
} else {
res.json(todo);
}
});
}
public getTodos(req: Request, res: Response): void {
Todo.find({}, (err, todos) => {
if (err) {
res.status(400).json(err);
} else {
res.json(todos);
}
});
}
public getTodoById(req: Request, res: Response): void {
Todo.findById(req.params.id, (err, todo) => {
if (err) {
res.status(400).json(err);
} else {
res.json(todo);
}
});
}
public updateTodo(req: Request, res: Response): void {
Todo.findByIdAndUpdate(req.params.id, req.body, { new: true }, (err, todo) => {
if (err) {
res.status(400).json(err);
} else {
res.json(todo);
}
});
}
public deleteTodo(req: Request, res: Response): void {
Todo.findByIdAndRemove(req.params.id, (err, todo) => {
if (err) {
res.status(400).json(err);
} else {
res.json(todo);
}
});
}
}
- Start your MongoDB server:
mongod
- Compile TypeScript and run the server:
npx tsc
node dist/server.js
Now, your TODO list backend should be running on http://localhost:3000/api
. You can use tools like Postman or CRUD to interact with the API or integrate it into a front-end application.
ย