I am trying to separate the connection to mongodb using nodejs and the current code looks like this in a file mongodb.js:
const mongoClient = require('mongodb').MongoClient;
const env = process.env.NODE_ENV || 'development';
const mongoDbUrl = require('../config/mongodb.json')[env];
let mongodb;
function connect(cb){
mongoClient.connect(mongoDbUrl.url, (err, db) => {
if (err) return "Could not connect to mongodb" ;
else{
console.log("Connection to mongodb is successful")
}
mongodb = db;
cb();
});
}
function get(){
return mongodb;
}
function close(){
mongodb.close();
}
module.exports = {
connect,
get,
close,
};
and in other files for ex app.js I use it as:
const mongodb = require('../config/mongodb');
mongodb.connect(() => {
mongodb.get().collection('tyk_organizations').find({}).toArray()
.then((users) => {
console.log('organizations ', users);
});
});
Error I get:
mongodb.get(...).collection is not a function