我正在嘗試這種方法,但我不確定是否每次都會創建一個新連接。
獲取MongoClient.js
const { MongoClient } = require('mongodb');
const serverURL = process.env['mongoServerURL']
module.exports = async function (){
const mongoClient = await new MongoClient(serverURL);
await mongoClient.connect();
return mongoClient;
}
然后在 app.js 中
const getMongoClient = require("./_helpers/getMongoClient.js")
module.exports = getMongoClient();
然后在一個資料庫 service.js
async function syncGuilds(client){
const mongoClient = await require("../app.js")
... some database operations
}
module.exports = syncGuilds
uj5u.com熱心網友回復:
Node 模塊本身是單例的,您無需擔心它們。一旦你的模塊被評估,它就不會被再次評估。因此,您將始終收到模塊的相同實體,即它不會創建 mongo 連接的多個實體。
您可以查看此鏈接和此鏈接以獲取更多詳細資訊。
uj5u.com熱心網友回復:
它不會每次都創建一個新連接,如果你想你可以在選項中指定最大連接池大小默認值為 5。檢查下面的鏈接
https://mongodb.github.io/node-mongodb-native/driver-articles/mongoclient.html#connection-pool-configuration
const mongodb = require("mongodb");
let client = new mongodb.MongoClient(
"url",
{
tls: true,
auth: { user: "myuser", password: "mypassword" },
useNewUrlParser: true,
useUnifiedTopology: true,
poolSize: 1,
maxPoolSize: 1,
}
);
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/381512.html
