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

时间:2021-03-24 07:55:28

标签: javascript node.js mongodb mongodb-query mongodb-nodejs-driver

这里是 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 函数。 db 连接成功。但问题是我不能重复使用 client。例如,我想为集合创建一个单独的目录。 (为了获得一个集合,我需要 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'

1 个答案:

答案 0 :(得分:1)

你必须在连接到 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 };