How do I make a var / object / module with a reference to a specific collection of the connected DB?
How do I make a module to export a reference to a specific collection to be used elsewhere:
Module connect-to-db.js
var MongoClient = require('mongodb').MongoClient;
var assert = require('assert');
var url = 'mongodb://<user>:<password>@..shard..mongodb.net:<port>/<collection>?ssl=true&replicaSet=..shard..&authSource=admin';
// This part works
MongoClient.connect(url, function(err, db) {
assert.equal(null, err);
console.log('Connected to external MongoDB server');
// db.close(); // not called to keep connection open
// How do I return db to the outside of this callback's scope
// to exports.user?
});
// This is the part that's not working
// How do I access db.collection('users').find() from outside this module
module.exports.users = MongoClient;
// this should return a reference to db.collection('users') in exports.users
// where should I return
Then be able to query / write to that collection from anywhere (using dBconnection.users as below):
Main App server.js
var express = require('express');
var app = express();
var dBconnection = require('./connect-to-db');
// is dBconnection is a reference to MongoClient.connection ?
// is dBconnection.users a reference to db.collection('users') ?
app.get('/db', function(req, res){
// From here does not work
records = dBconnection.users.find();
// runtime error: cannot use .find() of undefined
// OR runtime error: find() is not a function of users
// Testing the query
res.setHeader('Content-Type', 'text/plain');
res.write('Attempting to display records\n');
res.end(JSON.stringify(records, null, 2));
});
app.listen(3000, function () {
console.log('Listening at port 3000')
});
In the end I want to make the module maintain the connection (even if dropped, maybe adding a .status property to exports to check the status) so that I can access it anytime elsewhere in server.js / other modules / other routes / views