33
loading...
This website collects cookies to deliver better user experience
npm -v
and node -v
.// From the installation folder
mongo // it will start mongo terminal
use mern_todo // Creating new database mern_todo
// Setting up backend server
mkdir backend // creating backend folder
cd backend
npm init y // creating package.json file
npm i express body-parser cors mongoose
app.use(bodyParser.urlencoded({extended: true})); // Supports URL encoded bodies
app.use(bodyParser.json()); // Supports JSON encoded bodies
npm i -g nodemon
server.js
using which we will be configuring our backend service.// importing required packages
const express = require("express");
const app = express();
const bodyParser = require("body-parser");
const cors = require("cors");
const mongoose = require("mongoose");
const PORT = 4000;
// configuring the middleware
app.use(cors());
app.use(bodyParser.urlencoded({extended: true})); // Supports URL encoded bodies
app.use(bodyParser.json()); // Supports JSON encoded bodies
// connecting to database
mongoose.connect("mongodb://127.0.0.1:27017/mern_todo", {
useNewUrlParser: true,
});
const connection = mongoose.connection;
connection.once('open', function(){
console.log('MongoDB database connection established successfully');
});
// listening the request at port 4000
app.listen(PORT, function () {
console.log("Server is running on Port: " + PORT);
});
http://localhost:4000/
, you will see nothing. But in Terminal, you can see the output successfully.app.linsten
sectionapp.get('/',(_, response) => {
response.send("Hey, You can see me now!!!");
});
models
in root directory and add a todo.js
file.// importing required packages
const mongoose = require("mongoose");
const Schema = mongoose.Schema;
// declaring Todo schema
let Todo = new Schema ({
title: { type: String },
description: { type: String },
priority: { type: String },
completed: { type: Boolean },
});
// exporting to make it consumable
module.exports = mongoose.model('Todo', Todo);
mern_todo
database.routes
in root directory and add a todo_routes.js
file.// importing packages
const express = require("express");
const todoRoutes = express.Router();
// importing model to access todo collection in mern_todo database
let Todo = require('../models/todo');
// get - returns list of todos
todoRoutes.route("/").get(function (req, res) {
Todo.find(function (error, todos) {
if (error) {
console.log(error);
} else {
res.json(todos);
}
});
});
// get by id - returns single todo
todoRoutes.route("/:id").get(function (req, res) {
let id = req.params.id;
Todo.findById(id, function (error, todo) {
if (!todo) {
res.status(404).send("Todo not found");
}
res.json(todo);
});
});
// update - updates a todo at provided id
todoRoutes.route("/:id").put(function (req, res) {
let id = req.params.id;
Todo.findById(id, function (error, todo) {
if (!todo) {
res.status(404).send("Todo not found");
} else {
todo.title = req.body.title;
todo.description = req.body.description;
todo.priority = req.body.priority;
todo.completed = req.body.completed;
todo
.save()
.then((todo) => {
res.json("Todo updated");
})
.catch((error) => {
req.status(400).send("Update not possible");
});
}
});
});
// post - adds a todo
todoRoutes.route('/').post(function(req,res){
let todo = new Todo(req.body);
todo
.save()
.then((todo) => {
res.status(200).json({'todo': 'todo created successfully'});
})
.catch((error) => {
req.status(400).send("failed to create todo");
});
});
// delete - removes a todo
todoRoutes.route('/:id').delete(function(req,res){
let id = req.params.id;
Todo.findById(id, function (error, todo) {
if (!todo) {
res.status(404).send("Todo not found");
} else {
todo
.delete()
.then((todo) => {
res.status(200).json({'todo': 'todo deleted successfully'});
})
.catch((error) => {
req.status(500).send("failed to delete");
});
}
});
});
// exporting the todo routes
module.exports = todoRoutes;
...
...
app.use('/todos', todoRoutes);
app.listen(PORT, function () {
console.log("Server is running on Port: " + PORT);
});