Node.js 如何修复MongoError:服务器实例池被破坏?

Node.js 如何修复MongoError:服务器实例池被破坏?,node.js,mongodb,Node.js,Mongodb,我的目标是简单地将一条来自表单帖子的消息插入数据库 我在没有使用任何框架的情况下尝试了以下代码 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 =

我的目标是简单地将一条来自表单帖子的消息插入数据库

我在没有使用任何框架的情况下尝试了以下代码

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}/`);
});
consthttp=require('http');
const MongoClient=require('mongodb')。MongoClient;
var qs=要求(“查询字符串”);
var url=require('url');
常量主机名='127.0.0.1';
常数端口=3000;
常量uri=mongodb://localhost:27017';
const client=newmongoclient(uri,{useNewUrlParser:true});
var messages=“”;
const server=http.createServer((req,res)=>{
res.statusCode=200;
res.setHeader('Content-Type','text/html');
res.write(`
插入
);
如果(请求方法=='POST'){
变量体=“”;
请求开启(“数据”,功能(数据){
body+=数据;
});
请求开启('end',函数(){
var post=qs.parse(body);
client.connect(err=>{
const collection=client.db(“mydb”).collection(“消息”);
collection.insertOne(post,function(err,res){
如果(错误)抛出错误;
控制台日志(“插入1个文档”);
client.close();//要么把它放在这里,要么根本不关闭连接,仍然显示错误
})
});
});
} 
});
侦听(端口、主机名,()=>{
log(`Server running at http://${hostname}:${port}/`);
});
现在,当我运行该应用程序时,它会不断加载/请求,并在提交一条消息后抛出错误“MongoError:服务器实例池已销毁”。请帮助我实现目标的正确方法或解决方法。谢谢。

client.close()
在回调的“外部”调用,而回调需要“内部”。事实上,http服务器的代码根本不应该调用
client.close()
。请查看“第一个”链接副本,以参考回调及其与应用程序中的流控制的关系。有关如何在应用程序内正确处理连接的参考信息,请参阅。
client.close()
在回调的“外部”调用,而回调需要“内部”。事实上,http服务器的代码根本不应该调用
client.close()
。请查看“第一个”链接副本,以参考回调及其与应用程序中的流控制的关系。有关如何在应用程序中正确处理连接的参考,请参阅。