I want to use the promises function, where I can connect to mongodb synchronously, and I can reuse this connection by passing it to other modules.
Here is what I came up with
class MongoDB { constructor(db,collection) { this.collection = db.collection(collection); } find(query, projection) { if(projection) return this.collection.find(query, projection); else return this.collection.find(query); } } class Crew extends MongoDB { constructor(db) { super(db,'crews'); } validate() { } }
I want to establish a connection somewhere in my source code, as shown below, and then reuse the connection for different classes, just like a mongoose or monk does, but only uses its own node-mongodb package.
MongoClient.connect(url) .then( (err,dbase) => { global.DB = dbase; }); var Crew = new CrewModel(global.DB); Crew.find({}) .then(function(resp) { console.log(resp); });
At the moment, db is returning undefined inside the main MongoDB class, and I cannot debug it through Google or the documentation.
Edit: I assumed that the promise was synchronous, but it is not.
source share