[英]mongo client: how can I reuse the client in separate file?
這是 db.js 文件
const client = new MongoClient(DATABASE, mongodbOptions);
const connectWithMongoDb = () => {
client.connect((err) => {
if (err) {
throw err;
} else {
console.log('db connected');
}
});
};
module.exports = { client, connectWithMongoDb };
我從我的 server.js 中調用了 connectWithMongoDb function。 db 連接成功。 但問題是我不能重用client
。 例如,我想為 collections 創建一個單獨的目錄。 (為了獲得一個集合,我需要client
對象)
所以,這是我的 collection.js 文件
const { client } = require('../helpers/db-helper/db');
exports.collection = client.db('organicdb').collection('products');
但是一旦調用此文件(collection.js),問題就會出現。
我收到此錯誤:
throw new MongoError('MongoClient must be connected before calling MongoClient.prototype.db'
您必須在連接到 MongoDB 后獲得連接,您可以在任何地方使用它。
讀取 - https://mongodb.github.io/node-mongodb-native/api-generated/mongoclient.html
let client;
async function connect() {
if (!client) {
client = await MongoClient.connect(DATABASE, mongodbOptions)
.catch(err => { console.log(err); });
}
return client;
}
conet getConectedClient = () => client;
const testConnection = connect()
.then((connection) => console.log(connection)); // call the function like this
module.exports = { connect, getConectedClient };
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.