I am new to Node and Mongo, I was trying to connect to a mongo database in one file and export the database handler to many other files, so that I need not to connect to the database in all files which need a connection to it. Here is how I attempted to do it
// db.js
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 methods on it in another file as follows
var db = require('./db')
console.log(db.collection('col'))
but it throws a TypeError, saying that db.collection
is not a function. How can I access the methods on db handler in other files?
you need to export function and it need callback1. when the wanted parameter can't get, set the callback1 to callback2 about the async function.
db.js
const MongoClient = require('mongodb').MongoClient;
const assert = require('assert');
let callback, db;
// Connection URL
const url = 'mongodb://localhost:27017';
// Database Name
const dbName = 'myproject';
// Use connect method to connect to the server
MongoClient.connect(url, function(err, client) {
assert.equal(null, err);
console.log("Connected successfully to server");
db = client.db(dbName);
callback(db)
client.close();
});
module.exports = function(cb){
if(typeof db != 'undefined' ){
cb(db)
}else{
callback = cb
}
}
other.js
const mongo = require("./db");
mongo((db) => {
//here get db handler
})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With