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.