In modern web development, creating robust backend services is essential, especially when dealing with dynamic data like todos. In this tutorial, I will build a Todo Application backend using MongoDB as our database and Express.js as our server framework. We’ll leverage the Mongoose library to interact with MongoDB in a schema-based manner.
Getting Started
First things first, let’s set up our environment. Ensure you have Node.js installed, and then install the necessary dependencies:
npm install express mongoose –save
Connecting to MongoDB
To begin, import the required libraries:
const express = require('express');
const mongoose = require('mongoose');
Next, establish a connection to your MongoDB database:
mongoose.connect('your MongoDB connection string/collection_name');
Defining the Schema
Even though MongoDB is a schema-less database, Mongoose requires us to define a schema before creating models. Let’s define our Todo schema:
const todoSchema = mongoose.Schema({ title: String, description: String, isComplete: { type: Boolean, default: false }
});
Creating the Model
With the schema in place, let’s create a model for our Todo:
const todo = mongosse.model('todo' , todoSchema);
Get all Todos
app.get('/todos', async (req, res) => { try { const todos = await Todo.find({}); if (!todos) { res.status(404).json({ msg: "Data not found" }); } else { res.json({ todos }); } } catch (error) { res.status(500).json({ msg: error }); }
});
Create a new todo:
app.post('/create-todo', async(req, res) =>{ //create the todos const {title, descrption} = req.body; try{ await todo.create({ title, description }) res.json({ msg :"To do created" }) } catch(error){ res.status(411).json({ msg: "Error" }) } //write the logic of creating a todo
})
Update a Todo
app.put('/update-todo', async(req,res) =>{ //update the todo const {id} = req.body; try{ await todo.updateOne({ _id : id }, { isComplate : true }) res.json({ msg : "Task completed" }) } catch(error){ res.status(505).json({ msg : "Server Error" }) } })
Conclusion
In this tutorial, we’ve covered the basics of building a Todo Application backend using MongoDB and Express. We’ve learned how to define schemas, create models, and implement CRUD operations.
Please see the below Github link for the code:
https://github.com/tirthraval/todo-backend
Happy coding! 🚀
Discover more from Coursity
Subscribe to get the latest posts sent to your email.