0

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.

enter image description here

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.

Roshana Pitigala
  • 8,437
  • 8
  • 49
  • 80
  • 2
    You're doing it wrong. You absolutely never want to close the `client` in a `http` service, nor to you create connections per request. Just open the connection once and share the reference around. Just like the many approaches listed as answers show you. Also, 30 something connections is pretty ordinary and very low volume, as well as being very healthy. – Neil Lunn Apr 18 '19 at 10:58
  • The answers in the duplicate post were a bit heavy for a noob. Hence I found my own approach, check it out [here](https://stackoverflow.com/a/55762320/2408342). – Roshana Pitigala Apr 19 '19 at 13:06

0 Answers0