I am new to Node and Mongo, I tried to connect to the mongo database in one file and export the database handler to many other files, so I do not need to connect to the database in all the files that you need to connect to it. This is how I tried to do it
var client = require('mongodb').MongoClient
var assert = require('assert')
var url = 'mongodb://localhost:27017/test'
client.connect(url, (err, db) => {
assert.equal(err, null)
module.exports = db
})
After exporting the db handler, I tried to access them in another file as follows
var db = require('./db')
console.log(db.collection('col'))
but it raises a TypeError, saying it is db.collectionnot a function. How can I access db handler methods in other files?
source
share