Loading

Deno - CRUD using MongoDB

Deno - CRUD using MongoDB

Hello friends, hope you are doing well. Today we will see how our little Deno connect with DB. So it will be a very very interesting topic for you. Those are not checked our my earlier post about Deno just have it once...

DENO - A First Look

REST API using DENO

Well, so all set, build a CRUD application using Deno.

We will start from where we were at the last topic, I know you are very smart and checked my last topic. We already have an application where we build a REST API. Now its time to introduce DB so things will be in a complete shape. Here to make the thing simple we first connect a mongodb database.

So, we have already seen the app.ts it will be almost same with a little change. See below...

import { Application } from 'https://deno.land/x/oak/mod.ts';
import router from './router.ts';

const PORT = 8000;
const app = new Application();

app.use(router.routes());
app.use(router.allowedMethods());

console.log("Server is up and running in port:", PORT); 
app.listen({port: PORT});

Now, in router.ts we have declare all routing options.

import { Router } from 'https://deno.land/x/oak/mod.ts';
import { getEmployees, getEmployee, addEmployee, updateEmployee, deleteEmployee } from './controller.ts';

const router = new Router();

router
.get('/employees', getEmployees)
.get('/employee/:empId', getEmployee)
.post('/employee', addEmployee)
.put('/employee/:empId', updateEmployee)
.delete('/employee/:empId', deleteEmployee)
;
export default router;

Lastly we have to prepare the controller.ts. See the below code.

import db from "./mongodb.ts";

const empCollection = db.collection("employees");
const getEmployees = async ({ response }: { response: any }) => { 
    const employees = await empCollection.find();
    response.body = employees
};
const getEmployee = async ({ params, response }: { params: { empId: string }; response: any }) => {
    const employee = await empCollection.findOne({ empId: params.empId });
    if (employee) {
        response.status = 200
        response.body = employee
    } else {
        response.status = 404
        response.body = { message: 'Employee not found.' }
    } 
};
const addEmployee = async ({ request, response }: { request: any; response: any }) => {
    const body = request.body();
    const emp_val = await body.value; 
    const empId = emp_val.empId;
    const deptName = emp_val.deptName;
    const designation = emp_val.designation;

    const employee: any = { empId, deptName, designation};
    const newEmpId = await empCollection.insertOne(employee);

    response.body = { message: 'OK', data: newEmpId }
    response.status = 201
};

const updateEmployee = async ({ params, request, response }: { params: { empId: string }; request: any; response: any }) => {
    const employee = await empCollection.findOne({ empId: params.empId });
    if (employee) {
        const body = request.body();
        const emp_val = await body.value; 
        const deptName = emp_val.deptName;
        const designation = emp_val.designation;

        const { modifiedCount } = await empCollection.updateOne(
        { empId: params.empId }, 
        { $set: {deptName, designation }} 
       );

        if (modifiedCount) {
            response.status = 200
            const newEmployee = await empCollection.findOne({ empId: params.empId });
            response.body = { message: 'OK', data: newEmployee }
        } else {
            response.status = 404
            response.body = { message: `Employee not found` }
        } 
    }
};

const deleteEmployee = async ({ params, response }: { params: { empId: string }; response: any }) => {
    const count = await empCollection.deleteOne({ empId: params.empId });

    if (!count) {
        response.status = 404;
        response.body = { message: "Note does not exist" };
    } else {
        response.body = { message: 'OK' }
        response.status = 200
    }
};
export { getEmployees, getEmployee, addEmployee, updateEmployee, deleteEmployee }

Now we have to prepare the mongodb.ts here we need to first impor the MongoClient from Deno’s library.

import { MongoClient } from "https://deno.land/x/mongo/mod.ts";

const DB_URL = "mongodb://localhost:27017"
const mongo_client = new MongoClient();
mongo_client.connectWithUri(DB_URL);

const db = mongo_client.database('employees_db');

export default db;

Finally to start the server run the bellow command

deno run --allow-net --allow-write --allow-read --allow-plugin --unstable server.ts

Summary So you can see how we build an application using Deno + REST API + Mongodb. Keep explore our site we will again come back with more interesting articles in Deno.

We are on Facebook, Twitter, LinkedIn, Medium, Quora, Instagram, etc.

By the way, want to learn more about Deno? Just check out the official Deno documentation.

Related Articles