49
loading...
This website collects cookies to deliver better user experience
mkdir crud-API
cd crud-API
npm init -y
npm install mongoose express dotenv cors
npm install -D nodemon
index.js
and add the following-const express = require("express");
const PORT = 8000;
const app = express();
app.listen(PORT, async () => {
console.log(`server up on port ${PORT}`);
});
scripts
add this new script-"start": "nodemon index.js"
npm run start
it will show server up on port 8000 in the consolerouter.js
and add the following-const router = require("express").Router();
router.get("/", (req, res) => {
res.send("Let's build a CRUD API!");
});
module.exports = router;
index.js
and add a middleware like this-app.use(router);
const router = require("./router");
.env
and create a new variable MONGODB_URL
like this-MONGODB_URL=mongodb+srv://avneesh0612:password>@cluster0.wz3aq.mongodb.net/myFirstDatabase?retryWrites=true&w=majority
index.js
and add in the following for connecting our app to MongoDB-mongoose
.connect(process.env.MONGODB_URL, {
useNewUrlParser: true,
useUnifiedTopology: true,
})
.then(() => {
console.log("Connected to MongoDB");
})
.catch((err) => {
console.log(err);
});
const mongoose = require("mongoose");
npm start
const dotenv = require("dotenv");
dotenv.config();
Model
to keep things organized. So, create a new folder Model
and a file Todo.js
inside of it. Our model is going to have only 4 things- title
, description
, completed
, and createdAt
. So add the following in Todo.js
-const mongoose = require("mongoose");
const TodoSchema = new mongoose.Schema({
title: {
type: String,
required: true,
},
description: {
type: String,
},
completed: {
type: Boolean,
default: false,
},
createdAt: {
type: Date,
default: Date.now,
},
});
module.exports = mongoose.model("Todo", TodoSchema);
controllers
and Todo.js
inside of it. I am going to create a dummy function for now-const getTodos = (req, res) => {
res.send("I am the get todos route");
};
module.exports = {
getTodos,
};
router.js
and create a new get route like this-router.get("/todos", getTodos);
getTodos
-const { getTodos } = require("./controllers/Todo");
router.js
-router.post("/todos", createTodo);
const { getTodos, createTodo } = require("./controllers/Todo");
controllers/Todo.js
-const createTodo = (req, res) => {
const todo = new Todo({
title: req.body.title,
description: req.body.description,
completed: req.body.completed,
});
todo.save((err, todo) => {
if (err) {
res.send(err);
}
res.json(todo);
});
};
title
, description
, and completed
from the body and create a new Todo from the model that we created. Also, it will save it to to the database with the .save
function. We also need to import Todo
like this-const Todo = require("../model/Todo");
module.exports = {
getTodos,
createTodo,
};
{
"title": "Title 1",
"description": "Description 1",
"completed": false
}
index.js
just above app.use(router)
and below mongoose.connect add the following middlewares-app.use(cors());
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
const cors = require("cors");
getTodos
function that we created. So, replace the function with this-const getTodos = (req, res) => {
Todo.find((err, todos) => {
if (err) {
res.send(err);
}
res.json(todos);
});
};
router.js
-router.put("/todos/:todoID", updateTodo);
controllers/Todo.js
-const { getTodos, createTodo, updateTodo } = require("./controllers/Todo");
controllers/Todo.js
let's build our updateTodo
function-const updateTodo = (req, res) => {
Todo.findOneAndUpdate(
{ _id: req.params.todoID },
{
$set: {
title: req.body.title,
description: req.body.description,
completed: req.body.completed,
},
},
{ new: true },
(err, Todo) => {
if (err) {
res.send(err);
} else res.json(Todo);
}
);
};
title
, description
, and completed
from the request body and update it according to the id in the URL. So, in postman create a new PUT request to http://localhost:8000/todos/todo_id. You also need to provide data in the body-{
"title": "Title 3",
"description": "Description 3",
"completed": false
}
router.js
-router.delete("/todos/:todoID", deleteTodo);
const {
getTodos,
createTodo,
updateTodo,
deleteTodo,
} = require("./controllers/Todo");
Todo.js
-const deleteTodo = (req, res) => {
Todo.deleteOne({ _id: req.params.todoID })
.then(() => res.json({ message: "Todo Deleted" }))
.catch((err) => res.send(err));
};
module.exports = {
getTodos,
createTodo,
updateTodo,
deleteTodo,
};
git init
.gitignore
and add the node modules in it-/node_modules
git add .
git commit -m "your commit message"
node index.js
"start": "node index.js"
index.js
change port to this-const PORT = process.env.PORT || 8000;
git add .
git commit -m "fix: deploy errors"
git push