I think you have problem with your file structure. Probably you are not including db to your controller.
Please, create a new file and call it database.js
Design your database.js like this:
const { MongoClient } = require('mongodb');
class DatabaseSingleton {
constructor() {
const uri = process.env.DB_CONNECTION_STRING;
this.client = new MongoClient(uri, { useUnifiedTopology: true });
this.isConnected = false;
this.client.connect().then(()=>{this.isConnected = true});
}
/**
* Returns the promise of a Database object. (It waits until a connection to the database was successful)
* @returns {Promise<any>}
*/
get mongo() {
return new Promise(async (resolve, reject) => {
let timedOut = false;
setTimeout(()=>{timedOut = true}, 300 * 1000);
while (!this.isConnected && !timedOut){
await new Promise((resolve)=>{setTimeout(()=>{resolve()}, 100)}) // Snooze the thread for 100ms without blocking the event loop
}
if (timedOut){
reject(false);
} else {
resolve(this.client.db());
}
})
}
}
// *** Setting up singleton ***
const SINGLETON_KEY = Symbol.for("MyProject.MyDB");
var globalSymbols = Object.getOwnPropertySymbols(global);
var hasInstance = (globalSymbols.indexOf(SINGLETON_KEY) > -1);
// If there is no instance of the singleton, make the instance.
if (!hasInstance){
global[SINGLETON_KEY] = new DatabaseSingleton()
}
// Define a function to retrieve a singleton instance
var singleton = {};
Object.defineProperty(singleton, "instance", {
get: function(){
return global[SINGLETON_KEY];
}
});
// The singleton should never be changed
Object.freeze(singleton);
module.exports = singleton;
// *** End of singleton setup ***
And convert your controller something like:
const database = require('./database').instance;
app.post('/create-item', function(req, res) {
const db = await database.mongo; // Call db here
db.collection('item').insertOne({text: req.body.item}, function() {
res.send("Thanks for submitting the form.")
})