0

Here is db.js file


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. db connects successfully. but the problem is I can't reuse the client. for example, I want to make a separate directory for collections. (in order to get a collection I need client object)

So, here is my collection.js file

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.

I am getting this error:

throw new MongoError('MongoClient must be connected before calling MongoClient.prototype.db'
Tushar Gupta - curioustushar
  • 58,085
  • 24
  • 103
  • 107
Ashik
  • 2,888
  • 8
  • 28
  • 53

1 Answers1

1

You have to get the connection after connecting to MongoDB post that you can use it anywhere.

Read - 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 };
Tushar Gupta - curioustushar
  • 58,085
  • 24
  • 103
  • 107
  • after applying your code. I can't use `mongoClient.db` i am getting `can't read property db of null` – Ashik Mar 24 '21 at 08:31
  • well. now when I call the connectWithMongo(client) from another file. I am getting `TypeError: client.connect is not a function` – Ashik Mar 24 '21 at 08:44
  • you can check this: https://i.postimg.cc/wT3kGY9P/carbon.png – Ashik Mar 24 '21 at 08:49
  • @Ashik Check now, `const testConnection = getClient() .then((connection) => console.log(connection));` connection variable inside then block is the db connection. – Tushar Gupta - curioustushar Mar 24 '21 at 08:51
  • so , I have to call `getClient` on those files where I need client? – Ashik Mar 24 '21 at 09:06
  • yes, @Ashik ```getClient() .then((client) => { console.log(client) // here is your db client });``` – Tushar Gupta - curioustushar Mar 24 '21 at 09:25
  • @Ashik You can getClient() on app.start and other files you can use `getConectedClient()` to get db access without then block. – Tushar Gupta - curioustushar Mar 24 '21 at 09:55
  • you mean connect() on app.start and getConnectedClinet() on other files? I tried that. ```const client = getConectedClient(); const collection = client.db('organicdb').collection('products');``` but the problem is I am getting `can not read db of undefined` – Ashik Mar 24 '21 at 11:04
  • @Ashik in that case use `connect() .then((connection) => { console.log(connection); const collection = connection.db('organicdb').collection('products'); });` – Tushar Gupta - curioustushar Mar 24 '21 at 11:10
  • this is my repo. https://github.com/ashiqdev/mongo-client-boilerplate – Ashik Mar 24 '21 at 11:11
  • the only solution so for I got is create new client on each request. which is not good at all https://github.com/ashiqdev/mongo-client-boilerplate/blob/main/models/Collection.js – Ashik Mar 24 '21 at 11:33
  • Check this - https://github.com/ashiqdev/mongo-client-boilerplate/pull/1/commits/962c5ce5638718a48c1eb6d49cb7bef552534c32 – Tushar Gupta - curioustushar Mar 24 '21 at 11:47