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