简体   繁体   English

mongo 客户端:如何在单独的文件中重用客户端?

[英]mongo client: how can I reuse the client in separate file?

Here is db.js 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 };

I called the connectWithMongoDb function from my server.js.我从我的 server.js 中调用了 connectWithMongoDb function。 db connects successfully. db 连接成功。 but the problem is I can't reuse the client .但问题是我不能重用client for example, I want to make a separate directory for collections.例如,我想为 collections 创建一个单独的目录。 (in order to get a collection I need client object) (为了获得一个集合,我需要client对象)

So, here is my collection.js file所以,这是我的 collection.js 文件

const { client } = require('../helpers/db-helper/db');

exports.collection = client.db('organicdb').collection('products');

but the problem arises as soon as this file(collection.js) is called.但是一旦调用此文件(collection.js),问题就会出现。

I am getting this error:我收到此错误:

throw new MongoError('MongoClient must be connected before calling MongoClient.prototype.db'

You have to get the connection after connecting to MongoDB post that you can use it anywhere.您必须在连接到 MongoDB 后获得连接,您可以在任何地方使用它。

Read - https://mongodb.github.io/node-mongodb-native/api-generated/mongoclient.html读取 - 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM