Backend: ExpressJS, MongoDB, Mongoose
5 min readFeb 10, 2024
Hey, Lets create a backend server using ExpressJS , MongoDB and Mongoose.
- First create a folder and name it Todo. Next create an index.js file.
- On your terminal run:
npm init
// this will initialize your node js project and create a new package.json file
// alternativelly you can run
npm init -y
// next install the required dependencies
npm i express mongoose dotenv
Mongoose
- Mongoose library is a popular JS library that provides a schema-based solution for modelling application data and interacting with mongodb.
- it is a helper for nodejs applications that use mongodb as their database.
Express
- This is a popular web- framework for node.js that simplifies the process of building web applications and API’s
Dotenv
- This is a simple Nodejs module that helps you to manage your environment variables in your application. It secures any sensitive information you may have in your project.
- After installing the dependencies create a server as follows:
const express = require("express")
const app = express()
const port=8080
app.get("/",(res,req)=>{
res.get("Hello Kevin this is port harcort")
})
app.listen(port, ()=>{
console.log(`You are listening in port ${port}`)
})
- We use the “require” method to call the installed modules/dependencies.
- To run your server use node index.js in your server.
- in the last code block on the console.log — we have used backticks to create a template literal which will enable string interpolation.
- This is the response you will get when running : localhost:3000 on your web browser:
After this we will look into the CRUD operations:
(Disclaimer this code snippets are just examples the actual template is after this description)
- These are CREATE, READ UPDATE and DELETE
- within our Todo project we will supplement them as follows:
- CREATE == POST
- READ == GET
- UPDATE == PUT/PATCH
- DELETE == DELETE
CREATE(POST)
- We define routes to handle incoming POST requests to create new records
- Then we extract the data from the request body and save it to the db
- Next we send a response indicating success or failure
- This is how the block is to look:
app.post("/create",(req,res)=>{
// Extract data from request body
const newData - req.body
// Save the data to the database
// Eg. db,collection("items").insertOne(newData)
//Send response
res.send("New record created successfully")
})
READ(GET)
- We define the route to handle incoming Get requests to retrieve records.
- Fetch the data from the database
- Send the fetched data as a response as follows:
app.get("/",(req,res)=>{
// Fetch data from the database - MongoDb
// EG: db.collection ("items").find().toArray((err,data) => {...});
res.send("Data retrieved successfully")
})
Update(PUT/PATCH)
- This requires a unique parameter/ id since we are updating a specific key point
- Define a route to handle incoming PUT or PATCH requests to update existing records
- Extract the updated data from the request body
- update the corresponding record in the database
- Send a response indicating success or failure as follows:
app.put('/update/:id', (req, res) => {
const itemId = req.params.id;
const updatedData = req.body;
// Update record in database (e.g., MongoDB)
// Example: db.collection('items').updateOne({ _id: ObjectId(itemId) }, { $set: updatedData });
// Send response
res.send('Record updated successfully');
});
DELETE
- Define a route to handle incoming DELETE requests to delete existing records
- Extract the id of the record to be deleted from the request params
- Delete the corresponding record from the database.
- send a response indicating success or failure
- this also requires to delete a unique entity;
app.delete('/delete/:id', (req, res) => {
const itemId = req.params.id;
// Delete record from database (e.g., MongoDB)
// Example: db.collection('items').deleteOne({ _id: ObjectId(itemId) });
// Send response
res.send('Record deleted successfully');
});
Lets dive into the actual project below
- Within your root folder add a .env file
- Next navigate into the mongoDb website>(create an account if you haven’t)login>create project[todo-app]>Deploy Database and set everything to default>copy the user-password and align it in your dotenv file>create deployment then connect
- Connecting to the database:
- Upon connecting choose drivers, then copy the mongoDB url into the Dotenv file.
- Next install the mongodb package in your project as follows:
npm i mongodb
- Within your MongoDB site… navigate to browse collection and add Todos as both the database and the collection name.
- Let’s get into the other step mongoose
- next initialize the following steps:
require("dotenv").config()
const mongoose = require("mongoose")
const MONGO_DB = process.env.MONGODB_URL
mongoose.connect(MONGO_DB).then(()=>{
console.log("MongoDB connected successfully")
}).catch((error)=> {
console.error("MongoDB connection error", error)
})
- Your server should be running well.
- Create a folder within your project named model and in it(get it : init LOL) add a file named todo.js
- in your model>todo.js add the following block of code:
const mongoose = require("mongoose")
const {Schema} = mongoose
const toDoSchema = new Schema({
title:{
type:{String}
},
description:{
type:{String}
}
})
const todo = mongoose.model("Todo",toDoSchema)
module.exports = todo
- Next go back in your index.js file and lets create the CRUD operations as follows
//Get method
app.get("/todos",(req,res)=>{
try{
const toDo = await todo.find()
res.status(200).json(toDo)
}catch(err){
console.error("There is an error:",err)
res.status(500).json({err: "Internal error"})
}
})
//Create method
app.post("/todos/create",async (req,res)=>{
try{
const newToDo = await todo.create(req.body)
res.status(201).json(newToDo)
}catch(err){
console.error("There is an error:",err)
res.status(500).json({err: "Internal error"})
}
})
// put
app.put("/todos/:id", async(req,res)=>{
try{
const updatedToDo = await todo.findByIdAndUpdate(req.params.id, req.body,{
new:true
})
res.status(200).json(updatedToDo)
}
catch(err){
console.error("There is an error:",err)
res.status(500).json({err: "Internal error"})
}
})
// Delete
app.delete("/todos/:id", async(req,res)=>{
try{
await todo.findByIdAndDelete(req.params.id)
res.status(204).send()
}
catch(err){
console.error("There is an error:",err)
res.status(500).json({err: "Internal error"})
}
})
- Within your postman application, login and create a collection: name it todo
- Next create a collection by the name: Todo
- Add the get request as follows:
Before I forget: Add this code in your index.js
app.use(express.json())
- within your headers add this in the POST request
- This is a side by side illustration on the mongodbserver and the postman POST method
- next you can follow through deleting and fetching the data.
And with that marks the end of this tutorial.
Happy coding :-)