I'm very new to Node.js and MongoDB. This is the code which I have written to retrieve data.
const MongoClient = require('mongodb').MongoClient;
const uri = "mongodb+srv://username:password@dbname.mongodb.net/test?retryWrites=true";
const client = new MongoClient(uri, {
useNewUrlParser: true
});
var http = require('http');
http.createServer(function (req, res) {
res.writeHead(200, {
'Content-Type': 'text/plain'
});
client.connect(err => {
client.db("fsdb").collection("subs").find({
sub: /sometext/i
}).toArray(function (err, result) {
if (err) throw err;
res.end(JSON.stringify(result));
// client.close(); -----> MongoError: Topology was destroyed
});
});
}).listen(80);
This code works fine. But it opens a new connection on each request and leaves them open.
If I use client.close();
it gives me the error,
MongoError: Topology was destroyed
How can I close the connection after retrieving data?
Edit:
Hence the answers in the duplicate post were a bit heavy for a beginner, I found my own approach. Posted it as an answer here.