在 Express 中使用 MongoClient 的最佳方式是什么?客户端内部路由还是客户端内部路由?我已经看过一些关于两者的教程,但现在我很困惑应该遵循哪一个?
app.get('/',(req,res)=>{
MongoClient.connect('connection_str',(err,db)=>{
err? console.log(`Error: ${err}`) :
db.collection('collection_name',(err,docs)=>{
err? console.log(`Error: ${err}`) :
res.json(docs);
});
});
});
或
MongoClient.connect('connection_str',(err,db)=>{
app.get('/',(req,res)=>{
db.collection('collection_name',(err,docs)=>{
err? console.log(`Error: ${err}`) :
res.json(docs);
});
});
});
第一个看起来很安全,但在不同的路线上是多余的,而第二个对于不同的路线来说是理想的,我刚刚开始学习 meern 堆栈,只想使用 mongodb 的 native mongo 客户端而不是 mongoose。伙计们,最好的方法是什么?谢谢!
最佳答案
我不推荐您当前使用的任何方法。相反,我建议您创建一个数据库连接一次,然后为所有路由重用该连接,或者您也可以继续使用数据库池。
来自官方文档:
A Connection Pool is a cache of database connections maintained by the driver so that connections can be re-used when new connections to the database are required. To reduce the number of connection pools created by your application, we recommend calling MongoClient.connect once and reusing the database variable returned by the callback:
此示例展示了如何创建一次连接并重用该连接:
var MongoClient = require('mongodb').MongoClient;
var db;
// Initialize connection once
MongoClient.connect("mongodb://localhost:27017/integration_test", function(err, database) {
if(err) throw err;
db = database;
// Start the application after the database connection is ready
app.listen(3000);
console.log("Listening on port 3000");
});
// Reuse database object in request handlers
app.get('/',(req,res)=>{
db.collection('collection_name',(err,docs)=>{
err ? console.log(`Error: ${err}`) :
res.json(docs);
});
});
});
关于javascript - 构建 MongoClient 和表达 : Client inside routes or routes inside client? 的最佳方式是什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56846505/