[英]Node.js/Express: How Do I Share or Export Mongo Database Connection To Other Modules?
我正在嘗試與我的 Node.js 項目中的其他模塊共享 Mongo 連接。 嘗試使用導出的客戶端時,我總是收到undefined
或is not a function
。 在對數據庫執行操作之前,我還有一個關於檢測連接是否確實打開的問題。
似乎使用app.locals
是共享連接的正確方法,但我也無法正常工作。 以下是我目前所擁有的。 我已經嘗試了很多方法。 我在網上找到的大部分內容似乎都導出了 Mongo 節點驅動程序的方法,而不是連接本身。 這個想法是連接一次並且在應用程序關閉之前永遠不會斷開連接。
const client = new MongoClient(uri, {
useNewUrlParser: true,
useUnifiedTopology: true,
});
async function connect () {
app.locals.dbConnected = false;
try {
await client.connect();
app.locals.dbConnected = true;
module.exports = client;
} catch (e) {
console.error(e);
}
};
然后在另一個模塊中做類似的事情:
await client.db('syslogs').collection('production').insertOne(doc);
是否可以共享連接?
可以做類似下面的事情:
const client = new MongoClient(uri, {
useNewUrlParser: true,
useUnifiedTopology: true,
});
let __inst = null;
export default new Promise((resolve, reject) => {
if (__inst !== null) resolve(__inst);
// the open event is the key here
// like this we can handle error, close etc thru events as well
client.open((err, mongoInst) => {
if (err) reject(err);
__inst = mongoInst;
resolve(__inst);
});
});
然后在其他模塊中,您可以隨意使用導出客戶端。
謝謝。
我剛剛使用app.locals
讓它工作。
索引.js
const { MongoClient } = require("mongodb");
const client = new MongoClient(uri, {
useNewUrlParser: true,
useUnifiedTopology: true,
});
(async () => {
app.locals.dbConnected = false;
try {
await client.connect();
console.log("Connected to DB");
app.locals.client = client;
app.listen(PORT, HOST, () => {
console.log(`Running on http://${HOST}:${PORT}`);
});
} catch (e) {
console.error(e);
}
})();
然后在我的模塊中:
async function index (req, res) {
try {
let db = req.app.locals.client.db("admin");
await db.command({ ping: 1 });
console.log("pinged admin database");
}catch(err) {
console.log(err);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.