Click here to Skip to main content
15,843,144 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
I am trying write a program using nodejs-express and mongodb. I would send a post request and the filtered data from mongodb will be displayed on the html page.
The program works but the connection is being made only at the beginning. Once the first request is given, the connection with mongodb closes and it never connects again. I have to restart the program to get the conenction again.

The code is below:
Server.js
const express = require('express');
const app = express();

const bodyParser = require('body-parser');
let Util = require('./files/modules/acessdb');


app.use(bodyParser.urlencoded({extended:false}));

app.get('/',(req,res)=>{
    
    res.send("Working");
});

app.post('/getinput',(req,res)=>{
    console.log("Options ="+req.body.depart);

    let data = Util.getdata(req.body.depart,res);
    console.log("Data = ",data);

   // res.send(JSON.stringify(data));
});

const server = app.listen(8000,()=>{
    let host=server.address().address;
    let port = server.address().port;
    console.log("Server running at "+host+":"+port);
});


acessdb.js
function getdata(data,res){
    conn.stconnect((err)=>{
        if(err)
        throw err;
    });

    let html = "<html> <head> </head> <body> <table>";

    const db = conn.getdb;
    const collection = db().collection('Students');
    console.log("Server entered");
        val = async ()=>{
            try{
            let file = await collection.find({"Department":data}).toArray()
            console.log("data is ",file);

            console.log("Data here : ",data);

            console.log("Type = "+file.length);

            for(let i =0;i<file.length;i++){

               html+="<tr> <td> "+file[i].Name+"</td><td>"+file[i].Department+"</td><td>"+file[i].Semester;
               html+="</td></tr>";
                console.log("FIle :"+file[i].Name)

            }
            html+="</table></body>";

            

            res.send(html);
        }
        catch(e){
            throw e;
        }
        finally{
            conn.disconnect();
        }
    }
   let value = val();
}
module.exports = {getdata};    


connect.js
let { MongoClient } = require('mongodb');
const url = 'mongodb://127.0.0.1:27017/';
let client;
let dbname = 'College';
var db;
async function stconnect(callback){ 
     
    client = new MongoClient(url);
    await client.connect();
     db= client.db(dbname);
    
}

const getdb = ()=> db;

const disconnect = () =>client.close();

stconnect()
    .then(()=>{
        console.log("Server connected");
        return ;
    })
    .catch(console.error)
    .finally(()=>{
    });

module.exports ={stconnect,getdb,disconnect};


What I have tried:

I can remove the disconnect function but that will just keep the connection all the time. I want the connection to be made only during post request and disconnect after the request is processed.
Posted
Updated 1-May-23 2:41am
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900