【问题标题】:mongo client: how can I reuse the client in separate file?mongo 客户端:如何在单独的文件中重用客户端?
【发布时间】:2021-03-24 07:55:28
【问题描述】:

这里是 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'

【问题讨论】:

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


    【解决方案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 };
    

    【讨论】:

    • 应用您的代码后。我不能使用mongoClient.db 我得到can't read property db of null
    • 好吧。现在当我从另一个文件调用 connectWithMongo(client) 时。我收到TypeError: client.connect is not a function
    • 你可以检查这个:i.postimg.cc/wT3kGY9P/carbon.png
    • @Ashik 现在检查,const testConnection = getClient() .then((connection) => console.log(connection)); 里面的连接变量然后块是数据库连接。
    • 所以,我必须在需要客户端的那些文件上调用getClient
    猜你喜欢
    • 1970-01-01
    • 2019-04-15
    • 2022-10-19
    • 2010-12-25
    • 2018-10-27
    • 1970-01-01
    • 2014-10-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多