top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

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

+1 vote
272 views

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?

posted Oct 1, 2015 by Alok Sharma

Looking for an answer?  Promote on:
Facebook Share Button Twitter Share Button LinkedIn Share Button

Similar Questions
0 votes

I have 3 node replicates and i am using all the host in my connection string.Once i execute my node.js script i want to see which particular host it got connected to.
I can fire the following command in mongo shell but same is not working in node.js script, mostly says like "function is not defined"

hostnamedb.hostInfo().system.hostnamers.status().members.find(r=>r.state===1).name
TypeError: db.hostInfo is not a function
ReferenceError: hostname is not defined

Can someone help me how i can find the connected mongo instance server name using the node.js script?

0 votes

I am trying to use the truncate feature within YCSB to cause the db to truncate the data set to allow multiple runs against the DB to see the same DB state in spite of previous runs inserts.
I am using -p truncate=true. Is this the correct way to cause a truncate in Mongo.

0 votes

If you wanted to copy over the mongo database using mongos oplog, how would you do it? Suppose we start copying the database at time T and we finish the copying at time U. We have to read from the oplog from time T onward and apply oplog changes (which also may have been applied between time T and U). Do the oplog transactions have timestamps in them so we can discard records before time T? Are the operations idempotent if we apply them twice (because we are applying an operation already executed between time T and U)? Guess I am confused how to get the initial data before reading from the oplog to continue the real time updates.

...