//index.js
//npm install express
//npm install ejs

import express from 'express'
import path from 'path'

const app = express()

const port = process.env.PORT || 3000
process.env.TZ = "Asia/Phnom_Penh"
const __dirname = path.resolve()

import index from './routes/index.js'
import admin from './routes/admin.js'
import mydb from './models/conMongoDB.js'

app.use('/',async function(req,res,next){
    req.mydb = await mydb
    req.__dirname = __dirname
    next()
})

app.set('views', path.join(__dirname, 'views'))
app.set('view engine', 'ejs')
app.use(express.static(path.join(__dirname, 'public')))
app.use(express.urlencoded({extended:false}))
app.use(express.json())
                                  
app.use('/',index) 
app.use('/admin',admin) 

app.listen(port,function(){
    console.log(`This application is listening to the port: ${port}`)
})

export default app

 

//models/conMongoDB.js
//npm install mongodb
//npm install dotenv
 
import mongodb from 'mongodb'
const mymongo = mongodb.MongoClient
import dotenv from 'dotenv'
dotenv.config()
const url = process.env.DATABASE_URI
 
let resultPromise = new Promise(function(resolve,reject){
    mymongo.connect(url, {useUnifiedTopology:true}, function(err, db){
        if (err) throw err
        const mydb = db.db("blog")
        if(mydb){
            resolve(mydb)
            console.log('Connected to the main database!!')
        }else{
            reject("Error occured!")
        }
    })
})
 
async function awaitPromise(){
    let mydb = await resultPromise
    return mydb
}
 
export default awaitPromise()

 

GitHub: https://github.com/Sokhavuth/Blog_

Vercel: https://khmerweb-blog.vercel.app/