Welcome folks today in this tutorial we will be building a hapi.js crud rest API inside MongoDB database using the mongoose library in JavaScript all the source code of this application will be there as shown below.
Get Started
Not to get started guys we need to initialise a simple node JS project by executing the below commands that are shown below
first of all we need to create the package JSON file for our node JS project by executing the below command
Npm init -y
after that we need to install the required dependencies which are will be there inside this project
Npm i @hapi/ hapi
Npm i mongoose
As you can see that guys we are installing the hapi library for building the web server and also we are installing the mongoose library for interacting or connecting with the mongo DB database for building this crud rest API
Now where is we need to make the index.js purchase file which will be the starting point of this application so simply write the code which is shown below
index.js
Making the MongoDB Connection
Here guys we are making the connection to the MongoDB database using the mongoose library inside hapi.js web server so simply copy paste the below code inside your index.js file
1 2 3 4 5 6 7 8 9 10 |
'use strict'; //Import Hapi const Hapi = require('@hapi/hapi'); //Database configuration const mongoose = require('mongoose'); mongoose.connect('mongodb://localhost:27017/CRUD_App', { useNewUrlParser: true, useUnifiedTopology: true }) .then(() => console.log('MongoDB connected....')) .catch(err => console.log(err)); |
as you can see that guys we are importing the Hapi JS library in the very first line and then we are also making the connection to the MongoDB database for this we are importing the mongoose library and then it contains the connect method in order to connect to the database and inside this method we are passing the MongoDB URI and this URL contains the port number which is 27017 and also the database name of mongo db so you need to create the database before you make the connection so this will return either true or false depending upon whether the connection has been made or not so once the connection is made now we will make the schema or we will write the data which will be inserted into the database in the next step
Making the Schema
so now is we need to make the scheme of this thread applications will be defining all the columns and Fields which will be required for this application so simply copy paste the below code
1 2 3 4 5 |
let noteSchema = { title: String, important: Boolean, description: String } |
As you can see that guys we have three columns out their two fields are of string type and we have a simple single Boolean parameter also we have a title field which will be the actual title of the note we also have a description field which will be containing the description of the note and also we have a Boolean parameter which is important
Now in the next time guys we will be making the Collection which will be the actual table which will get inserted into the MongoDB database using the schema which we have defined earlier so the table name collection name will be notes we have created this as you can see in the above code
1 2 |
//Create Model const Note = mongoose.model('Notes', noteSchema); |
Making the CRUD Routes in Hapi.js
Now guys we will be writing the actual routes for the application These routes will be responsible for carrying out the CRUD operations which will be creating the note and reading all the notes and reading specific note updating the note and lastly a route for deleting the notes for all the four routes will be there in this so now we need to create these routes simply copy paste all this code inside your index.js file.
Initializing the Hapi.js Web Server
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
const init = async () => { //Server configuration const server = Hapi.server({ port: 3000, host: 'localhost', routes: { cors: true } }); await server.start(); console.log('Server running on %s', server.info.uri); }; //Error handling process.on('unhandledRejection', (err) => { console.log(err); process.exit(1); }); init(); |
As you can see that guys first of all we are initialising the hapi js web server and basically we are passing port number property as well and also in the second argument we are passing the cors property to true So this will prevent the cross origin problem to not occur
So now guys will be defining all the routes inside this hapi JS web server which will include all the methods which will be get post put and delete
1 2 3 4 5 6 7 8 |
//Heading server.route({ method: 'GET', path: '/', handler: (request, h) => { return '<h1>Note CRUD App</h1>'; } }); |
As you can see that guys we have a simple get request out here which will be serving the homepage of the application so whenever someone goes to the home page they will see a simple H1 heading which will be there
Creating the Record Using POST Request
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
//Create Note server.route({ method: 'POST', path: '/api/note', handler: async (request, h) => { let info = request.payload; console.log(info); let newInfo = new Note(info); await newInfo.save((err, task) => { if (err) return console.log(err); }) return h.response("Success"); } }); |
So now we can see that guys we are using the actual using the POST request and basically we are taking the input data using the payload parameter and then basically we are using the save method of MongoDB mongoose library to actually insert the note inside the MongoDB database and then after insertion we are returning a simple JSON response back to the client with the success message
Getting All the Notes
1 2 3 4 5 6 7 8 9 10 |
//Get list of Notes and filter the list using query parameters server.route({ method: 'GET', path: '/api/notes', handler: async (request, h) => { let params = request.query let infos = await Note.find(params).lean(); return h.response(infos); } }); |
Now guys we will be writing the get route for reading all the notes which are present inside the MongoDB database so hair specifically we are using the mongoose method which is find which will actually return all the records which is present inside the collection or table and then we are returning these as a JSON response to the client
Updating a Specific Note Using it’s ID
1 2 3 4 5 6 7 8 9 10 11 |
//Update Note server.route({ method: 'PUT', path: '/api/note/{id}', handler: async (request, h) => { let params = request.params.id; let info = request.payload; let infos = await Note.updateOne({ _id: params }, info).lean(); return h.response(infos); } }); |
Now I know to update a specific note we are receiving the ID parameter in the URL of the request your fetching there that ID using the Param property and also we are getting the actual record using the payload property so now for updating it we are using the update one method of mongoose library in order to update the specific node which is present inside the collection or table after the successful updation we are returning the specific JSON message back to the client that your record has been successfully updated
Deleting the Specific Note Using it’s ID
1 2 3 4 5 6 7 8 9 10 |
//Delete Note server.route({ method: 'DELETE', path: '/api/note/{id}', handler: async (request, h) => { let params = request.params.id; let infos = await Note.remove({ _id: params }); return h.response(infos); } }); |
Alaska is in order to delete a specific note from the collection of table we are receiving the ID of that note and here we are receiving that ID using the Param parameter and then we are calling the remove method of the mongoose library in order to remove that record from the database after the successful operation we are returning a successful JSON response back to the client that your record has been successfully deleted
Full Source Code
Wrapping this blog post. You can see the full source code of index.js
file which is shown below
index.js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 |
'use strict'; //Import Hapi const Hapi = require('@hapi/hapi'); //Database configuration const mongoose = require('mongoose'); mongoose.connect('mongodb://localhost:27017/CRUD_App', { useNewUrlParser: true, useUnifiedTopology: true }) .then(() => console.log('MongoDB connected....')) .catch(err => console.log(err)); //Define Schema let noteSchema = { title: String, important: Boolean, description: String } //Create Model const Note = mongoose.model('Notes', noteSchema); const init = async () => { //Server configuration const server = Hapi.server({ port: 3000, host: 'localhost', routes: { cors: true } }); //Heading server.route({ method: 'GET', path: '/', handler: (request, h) => { return '<h1>Note CRUD App</h1>'; } }); //Create Note server.route({ method: 'POST', path: '/api/note', handler: async (request, h) => { let info = request.payload; console.log(info); let newInfo = new Note(info); await newInfo.save((err, task) => { if (err) return console.log(err); }) return h.response("Success"); } }); //Get list of Notes and filter the list using query parameters server.route({ method: 'GET', path: '/api/notes', handler: async (request, h) => { let params = request.query let infos = await Note.find(params).lean(); return h.response(infos); } }); //Update Note server.route({ method: 'PUT', path: '/api/note/{id}', handler: async (request, h) => { let params = request.params.id; let info = request.payload; let infos = await Note.updateOne({ _id: params }, info).lean(); return h.response(infos); } }); //Delete Note server.route({ method: 'DELETE', path: '/api/note/{id}', handler: async (request, h) => { let params = request.params.id; let infos = await Note.remove({ _id: params }); return h.response(infos); } }); await server.start(); console.log('Server running on %s', server.info.uri); }; //Error handling process.on('unhandledRejection', (err) => { console.log(err); process.exit(1); }); init(); |