在 NodeJs 中处理 Mongodb 全局连接的最佳方法是什么 [英] What is best way to handle global connection of Mongodb in NodeJs
问题描述
我使用 Node-Mongo-Native 并尝试设置全局连接变量,但我对两种可能的解决方案感到困惑.你们能帮我找出哪一个是好的吗?1. 解决方案(这很糟糕,因为每个请求都会尝试创建一个新连接.)
I using Node-Mongo-Native and trying to set a global connection variable, but I am confused between two possible solutions. Can you guys help me out with which one would be the good one? 1. Solution ( which is bad because every request will try to create a new connection.)
var express = require('express');
var app = express();
var MongoClient = require('mongodb').MongoClient;
var assert = require('assert');
// Connection URL
var url = '[connectionString]]';
// start server on port 3000
app.listen(3000, '0.0.0.0', function() {
// print a message when the server starts listening
console.log("server starting");
});
// Use connect method to connect to the server when the page is requested
app.get('/', function(request, response) {
MongoClient.connect(url, function(err, db) {
assert.equal(null, err);
db.listCollections({}).toArray(function(err, collections) {
assert.equal(null, err);
collections.forEach(function(collection) {
console.log(collection);
});
db.close();
})
response.send('Connected - see console for a list of available collections');
});
});
解决方案(在应用程序初始化时连接并将连接字符串分配给全局变量).但我认为将连接字符串分配给全局变量不是一个好主意.
Solution ( to connect at app init and assign the connection string to a global variable). but I believe assigning connection string to a global variable is a not a good idea.
var mongodb;var url = '[connectionString]';MongoClient.connect(url, function(err, db) {
assert.equal(null, err);mongodb=db;});
var mongodb;
var url = '[connectionString]';
MongoClient.connect(url, function(err, db) {
assert.equal(null, err);
mongodb=db;
}
);
我想在应用初始化时创建一个连接并在整个应用生命周期中使用.
I want to create a connection at the app initialization and use throughout the app lifetime.
你们能帮帮我吗?谢谢.
Can you guys help me out? Thanks.
推荐答案
创建一个 Connection
单例模块来管理应用程序数据库连接.
Create a Connection
singleton module to manage the apps database connection.
MongoClient 不提供单例连接池,因此您不想在应用中重复调用 MongoClient.connect()
.用于包装 mongo 客户端的单例类适用于我见过的大多数应用.
MongoClient does not provide a singleton connection pool so you don't want to call MongoClient.connect()
repeatedly in your app. A singleton class to wrap the mongo client works for most apps I've seen.
const MongoClient = require('mongodb').MongoClient
class Connection {
static async open() {
if (this.db) return this.db
this.db = await MongoClient.connect(this.url, this.options)
return this.db
}
}
Connection.db = null
Connection.url = 'mongodb://127.0.0.1:27017/test_db'
Connection.options = {
bufferMaxEntries: 0,
reconnectTries: 5000,
useNewUrlParser: true,
useUnifiedTopology: true,
}
module.exports = { Connection }
在您require('./Connection')
的任何地方,Connection.open()
方法都可用,Connection.db
方法也可用code> 属性(如果已初始化).
Everywhere you require('./Connection')
, the Connection.open()
method will be available, as will the Connection.db
property if it has been initialised.
const router = require('express').Router()
const { Connection } = require('../lib/Connection.js')
// This should go in the app/server setup, and waited for.
Connection.open()
router.get('/files', async (req, res) => {
try {
const files = await Connection.db.collection('files').find({})
res.json({ files })
}
catch (error) {
res.status(500).json({ error })
}
})
module.exports = router
这篇关于在 NodeJs 中处理 Mongodb 全局连接的最佳方法是什么的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!