我正在尝试使用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};```
1条答案
按热度按时间pobjuy321#
在
accessdb.js
文件的try-catch块中,删除finally
部分。在成功执行
try-catch
块之后,将执行finally
块,在您的情况下,这将关闭数据库连接。