//pages/index.py
import Head from 'next/head'
import styles from '../styles/Home.module.css'
import mydbPromise from '../models/setcon'
export default function Home({isConnected}) {
return (
<div className={styles.container}>
<Head>
<title>ទំព័រដើម</title>
<meta name="description" content="Generated by create next app" />
<link rel="icon" href="/images/siteLogo.png" />
</Head>
<main className={styles.main}>
ត្រូវបានតភ្ជាប់ទៅមូលដ្ឋានទិន្នន័យ៖ {isConnected}
</main>
</div>
)
}
export async function getServerSideProps(context) {
try {
context.req.mydb = await mydbPromise
return {
props: { isConnected: 'Yes' },
}
} catch (e) {
console.error(e)
return {
props: { isConnected: 'No' },
}
}
}
//models/setcon.js
//npm install mongodb
import {MongoClient} from 'mongodb'
const mymongo = MongoClient
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("nblog")
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()
//.env.local
DATABASE_URI=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
SECRET_KEY=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx