Skip to content

WebNinjaDeveloper.com

Programming Tutorials




Menu
  • Home
  • Youtube Channel
  • Official Blog
  • Nearby Places Finder
  • Direction Route Finder
  • Distance & Time Calculator
Menu

Build a Koa.js Router CRUD REST API in MongoDB Database in Javascript Full Project For Beginners

Posted on October 9, 2022

Welcome folks today in this blog post we will be building a koa.js Router crud rest api using mongodb database in javascript. All the full source code of the application is shown below.

 

 

Get Started

 

 

In order to get started you need to initialize a new Koa.js project using the below command

 

 

npm init -y

 

 

This will create the package.json file for your koa.js project. Now you need to install the packages required as shown below

 

 

npm i koa

 

 

npm i mongodb

 

 

npm i @koa/router

 

 

As you can see we are installing the koa.js package and also we are installing the koa.js router package as well. For interacting with mongodb database we are installing mongodb library

 

 

npm i koa-bodyparser --save-dev

 

 

npm i uuid --save-dev

 

 

As you can see we are installing koa-bodyparser and uuid as dev dependencies for this project. uuid package allows you to generate random id’s for your crud rest api.

 

 

Connecting to MongoDB

 

 

Now first of all guys we will be connecting to Mongodb database inside Koa.js application. First of all make a dal folder inside the root directory of your project

 

 

Inside that dal directory make a index.js file and copy paste the following code

 

 

JavaScript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
const {MongoClient} = require("mongodb");
 
const client = new MongoClient('mongodb://localhost:27017', {
    useNewUrlParser: true,
    useUnifiedTopology: true
});
 
client.connect(err => {
    if(err){
        console.error(err);
        process.exit(-1);
    }
    console.log("Successfully connected to MongoDB");
})
 
module.exports = client;

 

 

As you can see we are importing MongoClient class from the mongodb package. This class allows us to connect to the database. As we are creating a new object of this class we are passing the full address of the database passing the port number and also in the second argument we are passing some options in the object.

 

And then we are calling the connect() method inside it to connect to the database. And then inside the callback we are printing out successfully connected to database. Lastly we are exporting this class as client.

 

 

Making the CRUD Rest API

 

 

Now inside the same folder we need to make another file called as product.dao.js which will list all the operations which needs to be performed inside the mongodb database. So here we will have four fields inside the table

 

  1. Product: String
  2. Description : String
  3. Price: Integer
  4. Quantity: Integer

 

Now we will write the product.dao.js file and copy paste the below code

 

 

JavaScript
1
2
3
4
5
6
//Require the MongoDB connection created in index.js and then mention the db name
//within db() and mention the collection name within collection()
const products = require('./index').db('koa').collection('products');
 
//Require ObjectId in order to access documents based on the _id
const ObjectId = require('mongodb').ObjectId;

 

 

As you can see we are importing the previously created file for reference of database connection variable. And now at the time of insertion we are calling two methods which is db method where you need to give the database name of mongodb and then we have the collection name in which you need to give collection or table name. At the time of running mongodb will automatically create the table. We are also including the ObjectId property from the mongodb database because it will be used in update and delete operations.

 

 

Save the Products in MongoDB

 

 

JavaScript
1
2
3
4
5
const save = async ({name, description, qty, price}) => {
    const result = await products.insertOne({name, description, qty, price});
    //returns the inserted data
    return result.ops[0];
}

 

 

As in this block of code we are writing the save function and we are receiving the name,description,qty and price of the products. In this async function we are using the await keyword we are using the insertOne method in mongodb library. Here in the arguments of this function we are passing the name,description,qty and price of the product to create a new record. And then we are returning the created Record from this function

 

 

Get All Records from the Mongodb Database

 

 

JavaScript
1
2
3
4
5
const getAll = async () =>{
    const cursor = await products.find();
    //Converts the result into an array
    return cursor.toArray();
}

 

 

Here in this block of code we are using the find() method of mongodb database. Find() method returns all the records which are present inside the mongodb database. And lastly we are converting all records to an Array of objects using the toArray() method.

 

 

Get a Specific Product By it’s ID

 

 

JavaScript
1
2
3
const getById = async (id) =>{
    return await products.findOne({_id:ObjectId(id)});
}

 

 

Here in this block of code we have a simple function which returns specific details about a certain product. Here we are receiving an argument id of that product. And using this id of the product we are returning the specific details using the findOne() method. Here we are passing the id of the product as an argument.

 

 

Update the Details of a Particular Product By It’s ID

 

 

JavaScript
1
2
3
4
5
const update = async (id, {name,description,qty,price}) =>{
    console.log(id);
    const result = await products.replaceOne({_id:ObjectId(id)}, {name,description,qty,price});
    return result.ops[0];
}

 

 

Here in this block of code we are using a update function in which we are receiving two arguments. First argument is the id of the product and second argument is the object containing the information which needs to be updated which contains the name,description,qty and price. And inside this function we are using the replaceOne() method inside mongodb database. And also in this function we are passing the id of the product and also passing the updated info of the product as an object. And lastly we are returning the updated object from this function.

 

 

Remove the Product Using it’s ID

 

 

JavaScript
1
2
3
const removeById = async id =>{
    await products.deleteOne({_id:ObjectId(id)});
}

 

 

Here in this block of code we have the delete product function inside this function we are receiving the id of the product that needs to be deleted. And inside this function we are using the deleteOne() method in mongodb database to remove the product by passing the id of the product as an argument.

 

Lastly we need to export all these methods using the export statement as shown below

 

 

JavaScript
1
module.exports = {getAll,getById,removeById,save,update};

 

 

Fullproducts.dao.js Source Code

 

 

JavaScript
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
//Require the MongoDB connection created in index.js and then mention the db name
//within db() and mention the collection name within collection()
const products = require('./index').db('koa').collection('products');
 
//Require ObjectId in order to access documents based on the _id
const ObjectId = require('mongodb').ObjectId;
 
//Create
//This method accepts a Product object with name, description, qty and price as parameter
//and inserts it to the product collection using the insertOne() method
const save = async ({name, description, qty, price}) => {
    const result = await products.insertOne({name, description, qty, price});
    //returns the inserted data
    return result.ops[0];
}
 
//Read All
//This method will retrieve all the products from the database
const getAll = async () =>{
    const cursor = await products.find();
    //Converts the result into an array
    return cursor.toArray();
}
 
//Read Specific Products
//This method will retrieve a specific product from the database based on the id
const getById = async (id) =>{
    return await products.findOne({_id:ObjectId(id)});
}
//Update
//This method accepts an id and a Product object with name, description, qty and price as parameter
//The id is the id of the product to edit and the product object is the product that has been edited
//The replaceOne() method is used to update the product
const update = async (id, {name,description,qty,price}) =>{
    console.log(id);
    const result = await products.replaceOne({_id:ObjectId(id)}, {name,description,qty,price});
    return result.ops[0];
}
//Remove
//This method accept the id of the product to be removed
//deleteOne() method is used to delete the product from the database
const removeById = async id =>{
    await products.deleteOne({_id:ObjectId(id)});
}
//Export the functions
module.exports = {getAll,getById,removeById,save,update};

 

 

Making the API of Products CRUD Operation

 

 

Here we will be building an api for products crud operation that we defined using the mongodb methods. So just create the api folder and inside it make a file called products.api.js and copy paste the below code

 

 

 

 

api/products.api.js

 

 

JavaScript
1
const {getAll, getById, removeById, save, update} = require('../dal/products.dao');

 

 

First of all we are importing all the methods for making the api. These methods are defined in the earlier step which directly modifies the database.

 

 

JavaScript
1
2
3
4
5
6
7
8
9
10
11
const createProduct = async ({name, description, qty, price}) => {
    //Create a product object
    const product = {
        name,
        description,
        qty,
        price
    }
    //Call the Save method and pass the Product object
    return await save(product);
}

 

 

As you can see in this block of code we are writing the createProduct() method which allows you to create a new product. Here in this function we are passing the whole object of a product. And here in this function we are calling the save() method that we defined earlier.

 

 

JavaScript
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
//Map the getAll() method
const getProducts = async ()=>{
    //
    return await getAll();
}
//Map the getById() method
const getProduct = async id =>{
    return await getById(id);
}
//Map the removeById() method
const deleteProduct = async id =>{
    return await removeById(id);
}
//Map the update method, Gets the id and Product object as parameters and the passes it to the
//update() method
const updateProduct = async (id,{name, description, qty, price})=>{
    return await update(id,{name, description, qty, price});
}
//Export the methods to be used in routes
module.exports = {
    createProduct,
    getProducts,
    getProduct,
    deleteProduct,
    updateProduct
}

 

 

Similarly as you can see we are defining all the crud operations which is update,delete and getting all the products or specific product by using it’s id. And in all the functions we are using the methods of the mongodb which allows you to interact with the database.

 

 

products.api.js

 

 

JavaScript
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
//Import the methods that we exported in products.dao.js
const {getAll, getById, removeById, save, update} = require('../dal/products.dao');
 
//Map the save() method
const createProduct = async ({name, description, qty, price}) => {
    //Create a product object
    const product = {
        name,
        description,
        qty,
        price
    }
    //Call the Save method and pass the Product object
    return await save(product);
}
//Map the getAll() method
const getProducts = async ()=>{
    //
    return await getAll();
}
//Map the getById() method
const getProduct = async id =>{
    return await getById(id);
}
//Map the removeById() method
const deleteProduct = async id =>{
    return await removeById(id);
}
//Map the update method, Gets the id and Product object as parameters and the passes it to the
//update() method
const updateProduct = async (id,{name, description, qty, price})=>{
    return await update(id,{name, description, qty, price});
}
//Export the methods to be used in routes
module.exports = {
    createProduct,
    getProducts,
    getProduct,
    deleteProduct,
    updateProduct
}

 

 

Making Routes for CRUD REST API in Koa.js Router

 

 

Now we will create the routes for crud rest api using the koa.js router. For this we need to make a new folder called routes and inside it we need to make a products.routes.js

 

 

 

products.routes.js

 

 

JavaScript
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
//Import @koa/router package to handle the routing
const Router = require("@koa/router");
//Import methods created in products.api file
const {createProduct, getProduct, getProducts,updateProduct,deleteProduct} =  require('../api/products.api');
 
//Define the prefix of the api
const router = new Router({
    prefix:'/products'
})
//GET request
router.get('/',async ctx=>{
    ctx.body= await getProducts() ;
})
//POST request
router.post('/',async ctx=>{
    //Get the product details from the body
    let product = ctx.request.body;
    product = await createProduct(product);
    //If the product is added successfully 200 status code is sent as the response
    ctx.response.status = 200;
    ctx.body = product;
})
//GET request to get a specific product
//:id is used to indicate that id is a parameter not a path
router.get('/:id',async ctx=>{
    const id = ctx.params.id;
    ctx.body = await getProduct(id);
})
//Delete Request
router.delete('/:id',async ctx=>{
    //Get the id from the url
    const id = ctx.params.id;
    await deleteProduct(id);
})
//Update request to update a specific product sent as the id
router.put('/:id',async ctx=>{
    //Get the id from the url
    const id = ctx.params.id;
    //Get the product details from the body
    let product = ctx.request.body;
    product = await updateProduct(id,product);
    ctx.response.status = 200;
    ctx.body = product;
 
})
//Export the router
module.exports = router;

 

 

As you can see inside the router file of koa.js we are first of all importing the koa.js router package and also we are defining different http requests which include the get request to get all the data and the post request which is used to create a new product. And then we are using the put request to update the product and delete request to delete the product. And here we are also initializing the koa.js router as well by providing the prefix  of /products

 

And also in each request we are also sending a json response to the client. Also we are sending the http status code as well.

 

 

Starting the Koa.js Web Server

 

 

Now lastly we will be starting the koa.js web server by modifying the index.js file by copy pasting the below code

 

 

index.js

 

 

JavaScript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
//Import Koa
const Koa = require('Koa');
//Import body-parser
const bodyParser = require('koa-bodyparser');
//Importing the routes
const productRoutes = require('./routes/products.routes');
 
//Start App
const app = new Koa();
 
//Using body parser
app.use(bodyParser());
 
//Registering the routes
app.use(productRoutes.routes()).use(productRoutes.allowedMethods());
 
//Setup the port
app.listen(3000);
 
console.log("Application is running on port 3000");

 

 

Here in this block of code we are importing the koa package. And also we are importing the koa-bodyparser. And also we are importing the productRoutes file which contains all the routes for this application. And after that we are initializing new object of Koa() class to start a new Koa.js web server. And also we are including the bodyparser() middleware to the Koa.js web server. And also we are importing the middleware of product routes and also allowedMethods() middleware.

 

And also we are starting the Koa.js web server at port 3000.

 

 

Testing the Koa.js CRUD REST API in Postman

 

 

 

 

 

As you can see inside this postman we are making the get request and also getting a list of array of objects. And also we see these products are stored inside the mongodb database.

 

Similarly we can make the requests for other crud operations as well.

 

 

Recent Posts

  • Android Kotlin Project to Load Image From URL into ImageView Widget
  • Android Java Project to Make HTTP Call to JSONPlaceholder API and Display Data in RecyclerView Using GSON & Volley Library
  • Android Java Project to Download Youtube Video Thumbnail From URL & Save it inside SD Card
  • Android Java Project to Embed Google Maps & Add Markers Using Maps SDK
  • Android Java Project to Download Random Image From Unsplash Using OkHttp & Picasso Library & Display it
  • Angular
  • Bunjs
  • C#
  • Deno
  • django
  • Electronjs
  • java
  • javascript
  • Koajs
  • kotlin
  • Laravel
  • meteorjs
  • Nestjs
  • Nextjs
  • Nodejs
  • PHP
  • Python
  • React
  • ReactNative
  • Svelte
  • Tutorials
  • Vuejs




©2023 WebNinjaDeveloper.com | Design: Newspaperly WordPress Theme