Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I export a mongo database handler in Node.js?

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?

like image 932
segmentationfaulter Avatar asked Sep 26 '22 14:09

segmentationfaulter


1 Answers

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
})
like image 154
Papandadj Avatar answered Sep 30 '22 08:09

Papandadj