We already know that in database terminology, CRUD stands for Create, Read, Update, and Delete. The majority of database driven applications use CRUD functionalities to interact with the database. In our case, we have been creating a callable object as a controller to pass data to the job template. To pull job items from MongoDB database, we need to add a few statements into the controller, an create another method in the model for job item.
// controller/admin/job.js
import config from '../../config.js'
import categories from '../../model/category.js'
import job from '../../model/job.js'
class Job{
constructor(){
(async () => {
this.config = await config()
})()
}
async getItem(req,res){
this.config.pageTitle = 'ទំព័រការងារ'
this.config.route = '/admin/job'
this.config.type = 'job'
this.config.categories = await categories.getAllItem(req)
this.config.items = await job.getItem(req,this.config.maxPosts)
this.config.count = await job.count(req)
res.render('base',{data: this.config})
}
async postItem(req,res){
await job.insertItem(req)
res.redirect('/admin/job')
}
}
export default await new Job()
// model/job.js
class Job{
async count(req){
return await req.mydb.collection('jobs').countDocuments()
}
async insertItem(req){
const id = Date.now() + Math.round(Math.random() * 1E9).toString()
let newJob = {
id: id,
title: req.body.title,
content: req.body.content,
categories: req.body.categories,
payable: req.body.payable,
email: req.body.email,
website: req.body.website,
thumb: req.body.thumb,
location: req.body.location,
postdate: new Date(),
closedate: req.body.closedate,
author: req.session.user.id
}
await req.mydb.collection("jobs").insertOne(newJob)
}
async getItem(req,amount){
return await req.mydb.collection('jobs').find().sort({data: -1,_id: -1}).limit(amount).toArray()
}
}
export default new Job()