1

My objective is to simply insert a message into database from a form post.

I have tried the following code without using any framework.

const http = require('http');
const MongoClient = require('mongodb').MongoClient;
var qs = require('querystring');
var url = require('url');

const hostname = '127.0.0.1';
const port = 3000;
const uri = 'mongodb://localhost:27017';
const client = new MongoClient(uri, { useNewUrlParser: true });
var messages = "";

const server = http.createServer((req,res) => {
 res.statusCode = 200;
 res.setHeader('Content-Type', 'text/html');
 res.write(`
  <!doctype html>
  <html>
  <body>
   <form action="/" method="post">
      <input type="text" name="message" />
      <button>Insert</button>
   </form>
  </body>
  </html>);
 if (req.method === 'POST') {
  var body = '';
  req.on('data', function (data) {
    body += data;
  });

  req.on('end', function () {
    var post = qs.parse(body);
    client.connect(err => {
       const collection = client.db("mydb").collection("messages");
       collection.insertOne(post, function(err, res) {
          if(err) throw err;
          console.log("1 document inserted");
          client.close(); // Either I place it here or don't close the connection at all still showing error
       })
    });
  });

 } 
});

server.listen(port, hostname, () => {
 console.log(`Server running at http://${hostname}:${port}/`);
});

Now when I run the app it constantly loading/requesting and after submitting a message its throwing error "MongoError: server instance pool was destroyed". Please assist me what is the proper way to achieve the goal or any workaround. Thanks.

  • 2
    `client.close()` is being invoked **"outside"** of a callback when it **needs to be "inside"**. In fact your code for a http server really should **never** call `client.close()` at all. Please look at the "first" linked duplicate for reference on callbacks and their relation to **flow control** in your application. Please also see the [second linked duplicate](https://stackoverflow.com/questions/24621940/how-to-properly-reuse-connection-to-mongodb-across-nodejs-application-and-module) for reference on how to handle connections properly within your application. – Neil Lunn Mar 23 '19 at 04:56

0 Answers0