Node.js 如何建立可以从其他文件访问的全局mongodb连接
我有一个主服务器文件index.js:Node.js 如何建立可以从其他文件访问的全局mongodb连接,node.js,mongodb,express,Node.js,Mongodb,Express,我有一个主服务器文件index.js: const express = require('express') const app = express() const route = require('./route') app.use('/main', route) app.listen(3000) 然后我有route.js文件: const express = require('express') const router = express.Router() router.get('
const express = require('express')
const app = express()
const route = require('./route')
app.use('/main', route)
app.listen(3000)
然后我有route.js文件:
const express = require('express')
const router = express.Router()
router.get('/', (req, res) => {
res.send('Hello from main')
})
module.exports = router
正如标题所示,我如何建立全局mongodb连接,从而不必在每条路由上建立到数据库的新连接?谢谢 我很惊讶没有答案。最常见的模式是在单独的模块中初始化数据库连接,并将其导入任何需要它的文件中 以下内容摘自这篇较长的文章,采用回调风格编写。我对其进行了一些更新,以保证其符合以下要求:
/* Callback Style */
const assert = require("assert");
const client = require("mongodb").MongoClient;
const config = require("../config");
let _db;
module.exports = {
getDb,
initDb
};
function initDb(callback) {
if (_db) {
console.warn("Trying to init DB again!");
return callback(null, _db);
}
client.connect(config.db.connectionString,
config.db.connectionOptions, connected);
function connected(err, db) {
if (err) {
return callback(err);
}
console.log("DB initialized - connected to: " +
config.db.connectionString.split("@")[1]);
_db = db;
return callback(null, _db);
}
}
function getDb() {
assert.ok(_db, "Db has not been initialized. Please called init first.");
return _db;
}
/******************************************************************/
//The client
const initDb = require("./db").initDb;
const getDb = require("./db").getDb;
const app = require("express")();
const port = 3001;
app.use("/", exampleRoute);
initDb(function (err) {
app.listen(port, function (err) {
if (err) {
throw err; //
}
console.log("API Up and running on port " + port);
});
);
function exampleRoute(req, res){
const db = getDb();
//Do things with your database connection
res.json(results);
}
这是一个基于承诺的版本,没有分号,这是我自己可能做的。这些功能都将成为项目间重用的候选功能
const assert = require("assert")
const client = require("mongodb").MongoClient
const config = require("../config")
let _db
module.exports = {
getDb,
initDb
}
function initDb() {
if (_db) {
console.warn("Trying to init DB again!");
return Promise.resolve(true)
}
return client.connect(config.db.connectionString,
config.db.connectionOptions)
}
function getDb() {
assert.ok(_db, "Db has not been initialized. Please called init first.")
return _db
}
//////////////////////
const {initDb, getDb} = require("./db")
const app = require("express")()
const port = 3001
app.use("/", exampleRoute)
initDb().
then(_ =>bootServer(port))
.catch(console.log)
function bootServer(port) {
app.listen(port, function (err) {
if (err) {
Promise.reject(err)
}
console.log("API Up and running on port " + port)
Promise.resolve()
})
}
function exampleRoute(req, res){
const db = getDb();
//Do things with your database connection
res.json(results);
}
我很惊讶没有人回答这个问题。最常见的模式是在单独的模块中初始化数据库连接,并将其导入任何需要它的文件中 以下内容摘自这篇较长的文章,采用回调风格编写。我对其进行了一些更新,以保证其符合以下要求:
/* Callback Style */
const assert = require("assert");
const client = require("mongodb").MongoClient;
const config = require("../config");
let _db;
module.exports = {
getDb,
initDb
};
function initDb(callback) {
if (_db) {
console.warn("Trying to init DB again!");
return callback(null, _db);
}
client.connect(config.db.connectionString,
config.db.connectionOptions, connected);
function connected(err, db) {
if (err) {
return callback(err);
}
console.log("DB initialized - connected to: " +
config.db.connectionString.split("@")[1]);
_db = db;
return callback(null, _db);
}
}
function getDb() {
assert.ok(_db, "Db has not been initialized. Please called init first.");
return _db;
}
/******************************************************************/
//The client
const initDb = require("./db").initDb;
const getDb = require("./db").getDb;
const app = require("express")();
const port = 3001;
app.use("/", exampleRoute);
initDb(function (err) {
app.listen(port, function (err) {
if (err) {
throw err; //
}
console.log("API Up and running on port " + port);
});
);
function exampleRoute(req, res){
const db = getDb();
//Do things with your database connection
res.json(results);
}
这是一个基于承诺的版本,没有分号,这是我自己可能做的。这些功能都将成为项目间重用的候选功能
const assert = require("assert")
const client = require("mongodb").MongoClient
const config = require("../config")
let _db
module.exports = {
getDb,
initDb
}
function initDb() {
if (_db) {
console.warn("Trying to init DB again!");
return Promise.resolve(true)
}
return client.connect(config.db.connectionString,
config.db.connectionOptions)
}
function getDb() {
assert.ok(_db, "Db has not been initialized. Please called init first.")
return _db
}
//////////////////////
const {initDb, getDb} = require("./db")
const app = require("express")()
const port = 3001
app.use("/", exampleRoute)
initDb().
then(_ =>bootServer(port))
.catch(console.log)
function bootServer(port) {
app.listen(port, function (err) {
if (err) {
Promise.reject(err)
}
console.log("API Up and running on port " + port)
Promise.resolve()
})
}
function exampleRoute(req, res){
const db = getDb();
//Do things with your database connection
res.json(results);
}
感谢您的快速回复!感谢您的快速回复!