Skip to content

Commit f477ee4

Browse files
committed
setup mongodb connection and create crud schema methods
1 parent 5644b10 commit f477ee4

File tree

2 files changed

+58
-0
lines changed

2 files changed

+58
-0
lines changed

Diff for: src/database/mongo.ts

+43
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
import mongoose from 'mongoose';
2+
import { ITodo, TodoSchema } from '../models/todo';
3+
4+
const uri = process.env.MONGO_URI ?? '';
5+
6+
async function connectDB() {
7+
try {
8+
await mongoose.connect(uri);
9+
console.log('MongoDB connected with Mongoose');
10+
} catch (error) {
11+
console.error('Error connecting to MongoDB:', error);
12+
process.exit(1);
13+
}
14+
}
15+
16+
async function getTodos() {
17+
const todos = await TodoSchema.find();
18+
return todos;
19+
}
20+
21+
async function addTodo(todo: ITodo) {
22+
const newTodo = new TodoSchema(todo);
23+
await newTodo.save();
24+
return newTodo;
25+
}
26+
27+
async function updateTodo(id: string, updateData: Partial<ITodo>) {
28+
const updatedTodo = await TodoSchema.findByIdAndUpdate(id, updateData);
29+
if (!updatedTodo) {
30+
throw new Error('Todo not found');
31+
}
32+
return updatedTodo;
33+
}
34+
35+
async function deleteTodo(id: string) {
36+
const deletedTodo = await TodoSchema.findByIdAndDelete(id);
37+
if (!deletedTodo) {
38+
throw new Error('Todo not found');
39+
}
40+
return 'Todo deleted successfully';
41+
}
42+
43+
export { connectDB, getTodos, addTodo, updateTodo, deleteTodo };

Diff for: src/models/todo.ts

+15
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
import mongoose from 'mongoose';
2+
3+
export interface ITodo extends Document {
4+
title: string;
5+
description?: string;
6+
completed: boolean;
7+
}
8+
9+
const todoSchema = new mongoose.Schema({
10+
title: { type: String, required: true },
11+
description: { type: String },
12+
completed: { type: Boolean, default: false },
13+
});
14+
15+
export const TodoSchema = mongoose.model<ITodo>('Todo', todoSchema);

0 commit comments

Comments
 (0)