我有多個連接到mongodb的問題。我使用node.js和貓鼬連接到mongo。 我的簡單網頁只是連接,執行少量查詢,然後關閉連接。但是當我重定向到另一個頁面時,連接會打開兩次。如果我重新加載/重定向頁面,另一個連接打開。不需要mongodb的多個連接
我通過
mongoose.connection.on('connected', function() {
console.log('Connected to mongo server.');
});
mongoose.connection.on('error', function (err) {
console.log('Could not connect to mongo server!');
});
mongoose.connect(mongoUrl);
連接到數據庫並斷開與
mongoose.connection.close(function(){
console.log('connection closed');
});
日誌顯示,該連接被關閉。但如果我刷新第4x頁,我在日誌中看到
Connected to mongo server.
Connected to mongo server.
Connected to mongo server.
Connected to mongo server.
我錯過了什麼?
MongoDB中的日誌是這樣的(我敢肯定,連接功能只調用一次)
Wed Feb 19 18:56:54.780 [initandlisten] connection accepted from 127.0.0.1:59777 #261 (1 connection now open)
Wed Feb 19 18:56:54.783 [initandlisten] connection accepted from 127.0.0.1:59778 #262 (2 connections now open)
Wed Feb 19 18:56:54.784 [initandlisten] connection accepted from 127.0.0.1:59779 #263 (3 connections now open)
Wed Feb 19 18:56:54.787 [initandlisten] connection accepted from 127.0.0.1:59780 #264 (4 connections now open)
Wed Feb 19 18:56:54.788 [initandlisten] connection accepted from 127.0.0.1:59781 #265 (5 connections now open)
Wed Feb 19 18:56:54.839 [conn261] end connection 127.0.0.1:59777 (4 connections now open)
Wed Feb 19 18:56:54.839 [conn262] end connection 127.0.0.1:59778 (3 connections now open)
Wed Feb 19 18:56:54.840 [conn263] end connection 127.0.0.1:59779 (2 connections now open)
Wed Feb 19 18:56:54.840 [conn264] end connection 127.0.0.1:59780 (2 connections now open)
Wed Feb 19 18:56:54.840 [conn265] end connection 127.0.0.1:59781 (1 connection now open)
整個代碼在GitHub上:https://github.com/kraag22/graphs/blob/master/app/mongo.js
是的,這也正是它。 「當服務器啓動時,您應該真的創建一個MongoDB連接,並讓所有請求共享相同的連接。」 – kraag22