A route to user page is already defined. We can use this route to pull user data from MongoDB database through a method in model folder. We could define this method as below:
// controller/admin/user.js
import config from '../../config.js'
import userDB from '../../model/user.js'
class User{
constructor(){
(async ()=>{
this.config = await config()
})()
}
async getItem(req,res){
this.config.pageTitle = 'ទំព័រអ្នកប្រើប្រាស់'
this.config.route = '/admin/user'
this.config.type = 'user'
this.config.count = await userDB.count(req)
this.config.items = await userDB.getItem(req,this.config.maxPosts)
res.render('base',{data:this.config})
}
async postItem(req,res){
userDB.postItem(req,res)
res.redirect('/admin/user')
}
}
export default await new User()
// model/user.js
import bcrypt from 'bcryptjs'
class User{
async count(req){
return await req.mydb.collection('users').countDocuments()
}
async postItem(req){
const id = Date.now() + Math.round(Math.random() * 1E9).toString()
const hashPassword = bcrypt.hashSync(req.body.password, 12)
let newUser = {
id: id,
title: req.body.title,
content: req.body.content,
thumb: req.body.thumb,
postdate: req.body.datetime,
role: req.body.category,
email: req.body.email,
password: hashPassword,
}
await req.mydb.collection("users").insertOne(newUser)
}
async getItem(req,amount){
return await req.mydb.collection('users').find().sort({date:-1,_id:-1}).limit(amount).toArray()
}
}
export default new User()