Nodejs Mongodb服务器连接问题

h5qlskok  于 2023-05-06  发布在  Go
关注(0)|答案(1)|浏览(164)

我正在尝试使用Nodejs - express连接到mongodb数据库。程序工作正常,我得到的查询和HTML输出。但是当我再次查询时,程序没有连接到mongodb数据库。我必须再次运行程序(node命令)以获得连接。我希望每次给出后查询时都发出该命令。
下面是代码

服务器.js

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);
});

accessdb.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

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};```
pobjuy32

pobjuy321#

accessdb.js文件的try-catch块中,删除finally部分。

try{
  ...
    }
    catch(e){
        throw e;
    }
 // remove the finally block
 let value = val();

在成功执行try-catch块之后,将执行finally块,在您的情况下,这将关闭数据库连接。

相关问题