0

I created a singleton to store a pool connection during the lifetime of the application :

var { MongoClient } = require("mongodb");
var credentials = require("./../database/credentials.json");

class MongoInstance {
  static _db;

  static isInitialized() {
    return MongoInstance._db ? true : false;
  }

  static async connect() {
    const client = new MongoClient("mongodb://localhost:27017");
    try {
      await client.connect();

      console.log("Connected successfully to server");
      MongoInstance._db = client.db(credentials.dbName);
      return "done";
    } catch (e) {
      console.error("MongoDB connection error: ", e);
    }
  }

  static closeConnection() {
    if (MongoInstance.isInitialized()) MongoInstance._db.client.close();
  }

  static get db() {
    if (MongoInstance.isInitialized()) return MongoInstance._db;
    else {
      MongoInstance.connect().then(() => {
        return MongoInstance._db;
      });
    }
  }
}

module.exports = MongoInstance;

I call this singleton with the following method :

var MongoInstance = require("./../database/mongodb");

....

const find = async function (collection, limit) {
  try {
    const query = {};
    const sort = { length: -1 };
    return await MongoInstance.db
      .collection(collection)
      .find(query)
      .sort(sort)
      .limit(+limit)
      .toArray();
  } catch (e) {
    console.error("ERROR MongoDB find(): ", e);
    return null;
  }
};

But I get this error :

ERROR MongoDB find(): TypeError: Cannot read property 'collection' of undefined

What does it mean ?

Link to the official doc : npm

mtnp
  • 314
  • 7
  • 24
  • Check this to learn about singletons: https://refactoring.guru/design-patterns/singleton – Ariel Aug 19 '21 at 20:17
  • Maybe this will help too: https://stackoverflow.com/questions/2885385/what-is-the-difference-between-an-instance-and-an-object – Ariel Aug 19 '21 at 20:18

0 Answers0