// index.js
// npm install express

import express from 'express'
const app = express()

import mydb from './models/conMongoDB.js'
app.use('/',async function(req,res,next){
    req.mydb = await mydb
    next()
})

import frontRouter from './routes/front.js'
import adminRouter from './routes/admin.js'
app.use('/',frontRouter)
app.use('/admin',adminRouter)

const port = process.env.PORT || 8000
app.listen(port,()=>{
  console.log(`This app is listening to the port ${port}`)
})

 

// models/conMongoDB.js
// npm install mongodb
// npm install dotenv
 
import {MongoClient} from 'mongodb'
import dotenv from 'dotenv'
dotenv.config()

const url = process.env.DATABASE_URI
 
let resultPromise = new Promise(function(resolve,reject){
    MongoClient.connect(url, {useUnifiedTopology:true}, function(err, db){
        if (err) throw err
        const mydb = db.db("sale")
        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()

 

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