MongoDb Node.js drivder语言 - 我是否必须为每个操作关闭和打开连接?



我正在阅读节点.js mongodb 驱动程序教程

在本教程下面的示例代码中,它会在客户端完成后立即关闭客户端以执行它想要执行的任何操作。

如果Web服务器不断与mongo交互,是否真的期望重新连接到MongoDB,然后在每次收到请求时关闭此过程的连接? 欢迎提出更好的实现建议:)

const MongoClient = require('mongodb').MongoClient;
const assert = require('assert');
// Connection URL
const url = 'mongodb://localhost:27017,localhost:27018/?replicaSet=foo';
// Database Name
const dbName = 'myproject';
// Create a new MongoClient
const client = new MongoClient(url);
// Use connect method to connect to the Server
client.connect(function(err) {
  assert.equal(null, err);
  console.log("Connected correctly to server");
  const db = client.db(dbName);
  client.close();
});

你可以使用它,它使用连接池不需要关闭连接。

var mongoose = require("mongoose"); 
var db = 'mongodb://localhost/dataBaseName';
mongoose.connect(db, {
    useNewUrlParser: true
});
var db = mongoose.connection;
db.on("error", console.error.bind(console, "connection error:"));
fs.readdirSync(__dirname + "/models").forEach(function (filename) {
    if (~filename.indexOf(".js")) require(__dirname + "/models/" + filename);
});
mongoose.set("useFindAndModify", false);
mongoose.set("useCreateIndex", true);

无需在同一运行时中多次关闭和打开连接。应用启动时连接一次。

最新更新