RESTful CRUD APIs using Node.js Base Structure
Mongoose is an Object Data Modeling (ODM) library for MongoDB and Node.js. It manages relationships between data, provides schema validation, and is used to translate between objects in code and the representation of those objects in MongoDB. We will use mongoose for interaction between Node.js and MongoDB.
Lets start
npm init -y
Install dependencies
npm i express mongoose dotenv
Lets create the server
var express = require('express');
const app = express();
const port = process.env.PORT || 5000;
app.listen(port, ()=>console.log(`App run successfully in the port ${port}`))
Lets create routes
var express = require('express');
const app = express();
const port = process.env.PORT || 5000;
app.get("/", ()=>{
res.send("Hello World");
})
app.listen(port, ()=>console.log(`App run successfully in the port ${port}`))
Lets configure and connect to the Database
var express = require('express');
const mongoose = require('mongoose')
require("dotenv/config");
const app = express();
const port = process.env.PORT || 5000;
mongoose.connect(process.env.DB_CONNECTION, {useNewUrlParser:true, useUnifiedTopology: true})
.then(()=> console.log("DB Connected"))
.catch((err)=> console.log(err))
app.get("/", ()=>{
res.send("Hello World");
})
app.listen(port, ()=>console.log(`App run successfully in the port ${port}`))
Lets create modal
const mongoose = require('mongoose');
let bookmarkSchema = mongoose.Schema({
"category" : String,
"url" : String,
"notes" : String,
"domain" : String,
"status" : Boolean,
"created_at": Date,
"updated_at": Date
})
module.exports = mongoose.model('Bookmark', bookmarkSchema);
Middlewares
var express = require('express');
const mongoose = require('mongoose')
require("dotenv/config");
const app = express();
const port = process.env.PORT || 5000;
mongoose.connect(process.env.DB_CONNECTION, {useNewUrlParser:true, useUnifiedTopology: true})
.then(()=> console.log("DB Connected"))
.catch((err)=> console.log(err))
app.get("/", ()=>{
res.send("Hello World");
})
app.use(express.json())
app.listen(port, ()=>console.log(`App run successfully in the port ${port}`))
Lets create more routes
//bookmarks.js
const express = require('express');
const router = express.Router();
const Bookmark = require('../modal/bookmarks');
//To get all bookmar
router.get("/", (req, res)=> {
Bookmark.find()
.then((resp)=>{ res.status(200).json(resp) })
.catch((err)=>{ res.status(400).json( { message: "Request Failed",statusCode: 400 } )
})
})
//To Create a new Bookmark
router.post("/", (req, res)=> {
const { category,url,notes,domain,status,created_at,updated_at } = req.body;
const newbookmark = new Bookmark({ category,url,notes,domain,status,created_at,updated_at });
newbookmark.save()
.then((resp)=>{ res.status(201).json(resp) })
.catch((err)=>{ res.status(400).json( { message: "Request Failed",statusCode: 400 } )
})
})
//To Delete a specific Bookmark
router.delete("/:id", (req, res)=> {
Bookmark.remove({_id: req.params.id})
.then((resp)=>{ res.status(200).json(resp) })
.catch((err)=>{ res.status(400).json( { message: "Request Failed",statusCode: 400 } )
})
})
//To Delete multiple Bookmark
router.post("/delete", (req, res)=> {
Bookmark.deleteMany({_id: list, list: {$in: req.body.list}})
.then((resp)=>{ res.status(200).json(resp) })
.catch((err)=>{ res.status(400).json( { message: "Request Failed",statusCode: 400 } )
})
})
//To Get specific Bookmark
router.get("/:id", (req, res)=> {
Bookmark.findById(req.params.id)
.then((resp)=>{ res.status(200).json(resp) })
.catch((err)=>{ res.status(400).json( { message: "Request Failed",statusCode: 400 } )
})
})
//To update specific Bookmark
router.patch("/:id", (req, res)=> {
Bookmark.updateOne({_id: req.params.id}, {$set: req.body})
.then((resp)=>{ res.status(200).json(resp) })
.catch((err)=>{ res.status(400).json( { message: "Request Failed",statusCode: 400 } )
})
})
module.exports = router;
Importing the router inside index file
var express = require('express');
const mongoose = require('mongoose')
require("dotenv/config");
const app = express();
const port = process.env.PORT || 5000;
const bookmarkRouter = require('./routes/bookmarks')
mongoose.connect(process.env.DB_CONNECTION, {useNewUrlParser:true, useUnifiedTopology: true})
.then(()=> console.log("DB Connected"))
.catch((err)=> console.log(err))
app.get("/", ()=>{
res.send("Hello World");
})
app.use(express.json())
app.use('/bookmark', bookmarkRouter);
app.listen(port, ()=>console.log(`App run successfully in the port ${port}`))
Which HTTP method should we use?
When constructing a REST API each HTTP method corresponds to an action against a resource served by the API.
GET — retrieve a particular resource’s object or list all objects
POST — create a new resource’s object
PATCH — make a partial update to a particular resource’s object
PUT — completely overwrite a particular resource’s object
DELETE — remove a particular resource’s object
Following are the APIs we created
GET http://localhost:5000/bookmark (To get all bookmark)
POST http://localhost:5000/bookmark (To create a new bookmarkt)
{
"category": "MongoDB",
"url": "www.sitepoint.com",
"notes": "About Angular",
"domain": "sitepoint",
"status": true
}
GET http://localhost:5000/bookmark/:id (To get a specific bookmark)
GET Ex : http://localhost:5000/bookmark/5f86a1cf00b887cce649c6a5
DELETE http://localhost:5000/bookmark/:id (To delete a specific bookmark)
DELETE Ex : http://localhost:5000/bookmark/5f86e8024887fe0e60336a1d
PATCH http://localhost:5000/bookmark/:id (To update a specific bookmark)
PATCH Ex : http://localhost:5000/bookmark/5f86a1cf00b887cce649c6a5
{
"category": "Java"
}
creating-restful-crud-apis-with-node-js-express-js-and-mongodb-from-scratch
Express and MySQL
How to Build and Structure a Node.js MVC Application (Hapi, SQLite, Nodejs)
CRUD on Array
building-a-node-js-rest-api-with-express