{"id":1879,"date":"2020-10-14T18:06:05","date_gmt":"2020-10-14T12:36:05","guid":{"rendered":"http:\/\/uitutorials.in\/wp\/?p=1879"},"modified":"2020-10-14T18:06:05","modified_gmt":"2020-10-14T12:36:05","slug":"restful-crud-apis-using-node-js-base-structure","status":"publish","type":"post","link":"https:\/\/uitutorials.in\/wp\/restful-crud-apis-using-node-js-base-structure\/","title":{"rendered":"RESTful CRUD APIs using Node.js Base Structure"},"content":{"rendered":"<p>RESTful CRUD APIs using Node.js Base Structure<\/p>\n<p>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.<\/p>\n<p><strong>Lets start<\/strong><br \/>\nnpm init -y<\/p>\n<p><strong>Install dependencies<\/strong><br \/>\nnpm i express mongoose dotenv<\/p>\n<p><strong>Lets create the server<\/strong><\/p>\n<pre class=\"line-numbers\"><code class=\"language-javascript\">var express = require('express');\r\nconst app = express();\r\nconst port = process.env.PORT || 5000;\r\n\r\napp.listen(port, ()=>console.log(`App run successfully in the port ${port}`))\r\n\r\n<strong>Lets create routes<\/strong>\r\nvar express = require('express');\r\nconst app = express();\r\nconst port = process.env.PORT || 5000;\r\n\r\napp.get(\"\/\", ()=>{\r\n\tres.send(\"Hello World\");\r\n})\r\napp.listen(port, ()=>console.log(`App run successfully in the port ${port}`))<\/code><\/pre>\n<p><strong>Lets configure and connect to the Database<\/strong><\/p>\n<pre class=\"line-numbers\"><code class=\"language-javascript\">var express = require('express');\r\nconst mongoose = require('mongoose')\r\nrequire(\"dotenv\/config\");\r\n\r\nconst app = express();\r\nconst port = process.env.PORT || 5000;\r\n\r\nmongoose.connect(process.env.DB_CONNECTION, {useNewUrlParser:true, useUnifiedTopology: true})\r\n.then(()=> console.log(\"DB Connected\"))\r\n.catch((err)=> console.log(err))\r\n\r\napp.get(\"\/\", ()=>{\r\n\tres.send(\"Hello World\");\r\n})\r\n\r\napp.listen(port, ()=>console.log(`App run successfully in the port ${port}`))<\/code><\/pre>\n<p><strong>Lets create modal<\/strong><\/p>\n<pre class=\"line-numbers\"><code class=\"language-javascript\">const mongoose = require('mongoose');\r\n\r\nlet bookmarkSchema = mongoose.Schema({\r\n    \"category\" : String,\r\n    \"url\" : String,\r\n    \"notes\" : String,\r\n    \"domain\" : String,\r\n    \"status\" : Boolean,\r\n    \"created_at\": Date,\r\n    \"updated_at\": Date\r\n})\r\n\r\nmodule.exports = mongoose.model('Bookmark', bookmarkSchema);<\/code><\/pre>\n<p><strong>Middlewares<\/strong><\/p>\n<pre class=\"line-numbers\"><code class=\"language-javascript\">var express = require('express');\r\nconst mongoose = require('mongoose')\r\nrequire(\"dotenv\/config\");\r\n\r\nconst app = express();\r\nconst port = process.env.PORT || 5000;\r\n\r\nmongoose.connect(process.env.DB_CONNECTION, {useNewUrlParser:true, useUnifiedTopology: true})\r\n.then(()=> console.log(\"DB Connected\"))\r\n.catch((err)=> console.log(err))\r\n\r\napp.get(\"\/\", ()=>{\r\n\tres.send(\"Hello World\");\r\n})\r\n\r\napp.use(express.json())\r\n\r\napp.listen(port, ()=>console.log(`App run successfully in the port ${port}`))<\/code><\/pre>\n<p><strong>Lets create more routes<\/strong><\/p>\n<p>\/\/bookmarks.js<\/p>\n<pre class=\"line-numbers\"><code class=\"language-javascript\">const express = require('express');\r\nconst router = express.Router();\r\nconst Bookmark = require('..\/modal\/bookmarks');\r\n\r\n\/\/To get all bookmar\r\nrouter.get(\"\/\", (req, res)=> {\r\n    Bookmark.find()\r\n        .then((resp)=>{ res.status(200).json(resp) })\r\n        .catch((err)=>{ res.status(400).json( { message: \"Request Failed\",statusCode: 400 } )\r\n    })\r\n})\r\n\r\n\/\/To Create a new Bookmark\r\nrouter.post(\"\/\", (req, res)=> {\r\n    const { category,url,notes,domain,status,created_at,updated_at } = req.body;\r\n    const newbookmark = new Bookmark({ category,url,notes,domain,status,created_at,updated_at });\r\n    newbookmark.save()\r\n        .then((resp)=>{ res.status(201).json(resp) })\r\n        .catch((err)=>{ res.status(400).json( { message: \"Request Failed\",statusCode: 400 } )\r\n    })\r\n})\r\n\r\n\/\/To Delete a specific Bookmark\r\nrouter.delete(\"\/:id\", (req, res)=> {\r\n    Bookmark.remove({_id: req.params.id})\r\n        .then((resp)=>{ res.status(200).json(resp) })\r\n        .catch((err)=>{ res.status(400).json( { message: \"Request Failed\",statusCode: 400 } )\r\n    })\r\n})\r\n\r\n\/\/To Delete multiple Bookmark\r\nrouter.post(\"\/delete\", (req, res)=> {\r\n    Bookmark.deleteMany({_id: list, list: {$in: req.body.list}})\r\n        .then((resp)=>{ res.status(200).json(resp) })\r\n        .catch((err)=>{ res.status(400).json( { message: \"Request Failed\",statusCode: 400 } )\r\n    })\r\n})\r\n\r\n\/\/To Get specific Bookmark\r\nrouter.get(\"\/:id\", (req, res)=> {\r\n    Bookmark.findById(req.params.id)\r\n        .then((resp)=>{ res.status(200).json(resp) })\r\n        .catch((err)=>{ res.status(400).json( { message: \"Request Failed\",statusCode: 400 } )\r\n    })\r\n})\r\n\r\n\/\/To update specific Bookmark\r\nrouter.patch(\"\/:id\", (req, res)=> {\r\n    Bookmark.updateOne({_id: req.params.id}, {$set: req.body})\r\n        .then((resp)=>{ res.status(200).json(resp) })\r\n        .catch((err)=>{ res.status(400).json( { message: \"Request Failed\",statusCode: 400 } )\r\n    })\r\n})\r\n\r\nmodule.exports = router;<\/code><\/pre>\n<p><strong>Importing the router inside index file<\/strong><\/p>\n<pre class=\"line-numbers\"><code class=\"language-javascript\">var express = require('express');\r\nconst mongoose = require('mongoose')\r\nrequire(\"dotenv\/config\");\r\n\r\nconst app = express();\r\nconst port = process.env.PORT || 5000;\r\nconst bookmarkRouter = require('.\/routes\/bookmarks')\r\n\r\nmongoose.connect(process.env.DB_CONNECTION, {useNewUrlParser:true, useUnifiedTopology: true})\r\n.then(()=> console.log(\"DB Connected\"))\r\n.catch((err)=> console.log(err))\r\n\r\napp.get(\"\/\", ()=>{\r\n\tres.send(\"Hello World\");\r\n})\r\n\r\napp.use(express.json())\r\napp.use('\/bookmark', bookmarkRouter);\r\n\r\napp.listen(port, ()=>console.log(`App run successfully in the port ${port}`))<\/code><\/pre>\n<p><strong>Which HTTP method should we use?<\/strong><\/p>\n<p>When constructing a REST API each HTTP method corresponds to an action against a resource served by the API.<br \/>\n<strong>GET \u2014<\/strong> retrieve a particular resource\u2019s object or list all objects<br \/>\n<strong>POST \u2014<\/strong> create a new resource\u2019s object<br \/>\n<strong>PATCH \u2014<\/strong> make a partial update to a particular resource\u2019s object<br \/>\n<strong>PUT \u2014<\/strong> completely overwrite a particular resource\u2019s object<br \/>\n<strong>DELETE \u2014<\/strong> remove a particular resource\u2019s object<\/p>\n<p><strong>Following are the APIs we created<\/strong><\/p>\n<p><strong>GET <\/strong>http:\/\/localhost:5000\/bookmark (To get all bookmark)<br \/>\n<strong>POST <\/strong>http:\/\/localhost:5000\/bookmark (To create a new bookmarkt)<\/p>\n<pre class=\"line-numbers\"><code class=\"language-javascript\">{\r\n    \"category\": \"MongoDB\",\r\n    \"url\": \"www.sitepoint.com\",\r\n    \"notes\": \"About Angular\",\r\n    \"domain\": \"sitepoint\",\r\n    \"status\": true\r\n}<\/code><\/pre>\n<p><strong>GET <\/strong>http:\/\/localhost:5000\/bookmark\/:id (To get a specific bookmark)<br \/>\nGET Ex : http:\/\/localhost:5000\/bookmark\/5f86a1cf00b887cce649c6a5<\/p>\n<p><strong>DELETE <\/strong>http:\/\/localhost:5000\/bookmark\/:id (To delete a specific bookmark)<br \/>\nDELETE Ex : http:\/\/localhost:5000\/bookmark\/5f86e8024887fe0e60336a1d<\/p>\n<p><strong>PATCH <\/strong>http:\/\/localhost:5000\/bookmark\/:id (To update a specific bookmark)<br \/>\nPATCH Ex : http:\/\/localhost:5000\/bookmark\/5f86a1cf00b887cce649c6a5<\/p>\n<pre class=\"line-numbers\"><code class=\"language-javascript\">{\r\n    \"category\": \"Java\"\r\n}\r\n<\/code><\/pre>\n<p><a href=\"https:\/\/medium.com\/@jeyanthkanagaraju\/creating-restful-crud-apis-with-node-js-express-js-and-mongodb-from-scratch-3ef632067928\" rel=\"noopener\" target=\"_blank\">creating-restful-crud-apis-with-node-js-express-js-and-mongodb-from-scratch<\/a><br \/>\n<a href=\"https:\/\/www.js-tutorials.com\/nodejs-tutorial\/node-js-rest-api-add-edit-delete-record-mysql-using-express\/\" rel=\"noopener\" target=\"_blank\">Express and MySQL<\/a><br \/>\n<a href=\"https:\/\/www.sitepoint.com\/node-js-mvc-application\/\" rel=\"noopener\" target=\"_blank\">How to Build and Structure a Node.js MVC Application (Hapi, SQLite, Nodejs)<\/a><br \/>\n<a href=\"https:\/\/medium.com\/javascript-in-plain-english\/create-rest-api-web-services-using-node-js-and-express-js-with-crud-operations-ff790d6ae030\" rel=\"noopener\" target=\"_blank\">CRUD on Array<\/a><br \/>\n<a href=\"https:\/\/medium.com\/@jeffandersen\/building-a-node-js-rest-api-with-express-46b0901f29b6\" rel=\"noopener\" target=\"_blank\">building-a-node-js-rest-api-with-express<\/a><\/p>\n","protected":false},"excerpt":{"rendered":"<p>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<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[12,1],"tags":[63,20],"class_list":["post-1879","post","type-post","status-publish","format-standard","hentry","category-mongodb","category-nodejs","tag-mongoose-crud","tag-nodejs","ct-col-2"],"_links":{"self":[{"href":"https:\/\/uitutorials.in\/wp\/wp-json\/wp\/v2\/posts\/1879","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/uitutorials.in\/wp\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/uitutorials.in\/wp\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/uitutorials.in\/wp\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/uitutorials.in\/wp\/wp-json\/wp\/v2\/comments?post=1879"}],"version-history":[{"count":4,"href":"https:\/\/uitutorials.in\/wp\/wp-json\/wp\/v2\/posts\/1879\/revisions"}],"predecessor-version":[{"id":1883,"href":"https:\/\/uitutorials.in\/wp\/wp-json\/wp\/v2\/posts\/1879\/revisions\/1883"}],"wp:attachment":[{"href":"https:\/\/uitutorials.in\/wp\/wp-json\/wp\/v2\/media?parent=1879"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/uitutorials.in\/wp\/wp-json\/wp\/v2\/categories?post=1879"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/uitutorials.in\/wp\/wp-json\/wp\/v2\/tags?post=1879"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}