Settings are used to setup everything in the application. So, all data relating to settings must be a kind of persistent data that need to be stored in a separate collection in MongoDB database. To achieve this goal, we have to create a post route linked to a controller and a model.
// route/admin/setting.js
import express from 'express'
const settingRoute = express.Router()
import setting from "../../controller/admin/setting.js"
settingRoute.get('/',async (req,res)=>{
if(req.session.user){
setting.getItem(req,res)
}else{
res.redirect('/login')
}
})
settingRoute.post('/',async (req,res)=>{
if(req.session.user){
setting.postItem(req,res)
}else{
res.redirect('/login')
}
})
export default settingRoute
// controller/admin/setting.js
import config from '../../config.js'
import settingDB from "../../model/setting.js"
class Setting{
constructor(){
(async ()=>{
this.config = await config()
})()
}
async getItem(req,res){
this.config.pageTitle = 'ទំព័រ Setting'
this.config.route = '/admin/setting'
res.render('base',{data:this.config})
}
async postItem(req,res){
if(req.session.user.role === 'Admin'){
settingDB.postItem(req)
}
res.redirect('/admin/setting')
}
}
export default await new Setting()
// model/setting.js
class Setting{
async postItem(req){
const settings = {
siteTitle: req.body.siteTitle,
description: req.body.description,
maxPosts: req.body.description,
indexPostLimit: req.body.indexPostLimit,
categoryPostLimit: req.body.categoryPostLimit,
}
await req.mydb.collection('settings').insertOne(settings)
}
}
export default new Setting()