前提・実現したいこと
ExpressでMongoDBのAPIサーバを作ろうとしています。
MongoDBにはclient.connect()
で接続することができ、用が済んだらclient.close()
で閉じます。
このコネクションというものは、Expressのappが動いている間、一つのコネクションでいいのでしょうか?それとも、appがGETリクエストやらPUTリクエストやらを受け取る度にconnect
とclose
をした方がいいのでしょうか?
該当のソースコード
サンプルコードです。
出典
https://docs.mongodb.com/drivers/node/fundamentals/connection
JavaScript
1const { MongoClient } = require("mongodb"); 2 3// Connection URI 4const uri = 5 "mongodb+srv://sample-hostname:27017/?poolSize=20&w=majority"; 6 7// Create a new MongoClient 8const client = new MongoClient(uri); 9 10async function run() { 11 try { 12 // Connect the client to the server 13 await client.connect(); 14 15 // Establish and verify connection 16 await client.db("admin").command({ ping: 1 }); 17 console.log("Connected successfully to server"); 18 } finally { 19 // Ensures that the client will close when you finish/error 20 await client.close(); 21 } 22} 23run().catch(console.dir);
回答1件
あなたの回答
tips
プレビュー