There are four operations we can use to interact with the database. They are called CRUD (create, read, update, delete) operations. To begin, we can start to implement “C” operation by creating a number of categories for our job announcement by writing the codes as below:

 

// route/admin/category.js
import express from "express"
const categoryRoute = express.Router()
import category from '../../controller/admin/category.js'

categoryRoute.get('/',async (req,res,next) => {
    if(req.session.user){
        category.getItem(req,res)
    }else{
        res.redirect('/login')
    }
})

categoryRoute.post('/',async (req,res,next) => {
    if(req.session.user){
        category.postItem(req,res)
    }else{
        res.redirect('/login')
    }
})

export default categoryRoute

 

// controller/admin/category.js
import config from '../../config.js'
import categoryDB from '../../model/category.js'

class Category{
    constructor(){
        (async () => {
            this.config = await config()
        })()
    }

    getItem(req,res){
        this.config.pageTitle = 'ទំព័រ​ជំពូក'
        this.config.route = '/admin/category'
        this.config.type = 'category'

        res.render('base',{data:this.config})
    }

    async postItem(req,res){
        await categoryDB.insertItem(req,res)
        res.redirect('/admin/category')
    }
}

export default await new Category()

 

// model/category.js

class Category{

    async insertItem(req,res){
        const id = Date.now() + Math.round(Math.random() * 1E9).toString()
 
        let myCategory = {
            id: id, 
            title: req.body.title,
            thumb: req.body.thumb,
            date: req.body.datetime
        }
 
        await req.mydb.collection("categories").insertOne(myCategory)
    }
}

export default await new Category()

 

GitHub: https://github.com/Sokhavuth/khmerweb-job

Heroku: https://khmerweb-job.herokuapp.com