I using 节点-Mongodb-Native https://github.com/mongodb/node-mongodb-native并尝试设置全局连接变量,但我对两种可能的解决方案感到困惑。大家能帮我看看哪一款比较好吗?
1.解决方案(这很糟糕,因为每个请求都会尝试创建一个新连接。)
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');
});
});
-
解决方案(在应用程序初始化时连接并将连接字符串分配给全局变量)。但我相信将连接字符串分配给全局变量并不是一个好主意。
var mongodb;
var url = '[连接字符串]';
MongoClient.connect(url, 函数(err, db) {
断言.equal(null, err);
mongodb=数据库;
}
);
我想在应用程序初始化时创建连接并在整个应用程序生命周期中使用。
你们能帮我一下吗?谢谢。
创建一个Connection
单例模块来管理应用程序数据库连接。
MongoClient不提供单例连接池所以你不想调用MongoClient.connect()
在您的应用程序中重复。包装 mongo 客户端的单例类适用于我见过的大多数应用程序。
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')
, the Connection.open()
方法将可用,并且Connection.db
属性(如果已初始化)。
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
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)