Challenges in establishing the initial connection between Express.js and MongoDB

Having spent a significant amount of time researching how to set up MongoDb in an Express/NodeJs application, I believed I had a good understanding of how to implement it efficiently. I decided to initialize my mongodbConnection in the WWW file provided by Express, ensuring that only one connection is opened when the app starts.

WWW

!/usr/bin/env node
var debug = require('debug')('myapp');
var app = require('../app');
var mongoConnection = require('../mongo/mongoconnection.js');

mongoConnection.init(function(error){
    // Start the application after the database connection is ready
    app.set('port', process.env.PORT || 3000);

    var server = app.listen(app.get('port'), function() {
        debug('Express server listening on port ' + server.address().port);
    });
});

The actual initialization of the database is worked out in my mongoConnection.js file where I export the database variable.

mongoconnection.js

var mongodb = require('mongodb');
var bson = mongodb.BSONPure;
var MongoClient = mongodb.MongoClient;

// Initialize connection once
module.exports.init = function(callback)
{
    MongoClient.connect("mongodb://localhost:27017/capturemongo", function(err, database) {
        if(err) throw err;
        module.exports.db = database;
        callback(err);
    }); 
};

However, when trying to access the database variable from my mastermanager.js file, the db variable appears to be undefined.

mastermanager.js

var mongoConnection = require('./mongoconnection.js');
var db = mongoConnection.db;

module.exports.getCollection = function( callback){
    db.collection('masters', function(err, collection){
        if(!err){
            callback(null, collection);
        }
        else{
            console.log("getcolelction error " + err);
            callback(err);
        }
    });
};

module.exports.findAll = function(callback) {
    this.getCollection(function(error, collection) {
      if( error ){
          callback(error);
      }
      else {
        collection.find().toArray(function(error, results) {
          if( error ) {
              callback(error);
              console.log('finderror ' + error);
          }
          else{ 
              console.log(results);
              callback(null, results);
          }
        });
      }
    });
};

I am struggling to understand why the variable is undefined there. When adding console.log() statements in the init of mongoconnection, it clearly shows that the database variable is set!

Any assistance would be greatly appreciated!

Answer №1

It seems that mastermanager.js may not be required in the code snippet provided. However, it appears that module.exports.db is being set within a callback function, which could potentially lead to issues if mastermanager.js is required after this callback is executed.

To avoid any potential problems, you might consider reorganizing your code by moving the declaration of db to a point where it will be used immediately, as demonstrated below:

module.exports.getCollection = function(callback) {
    var db = mongoConnection.db;
    db.collection('masters', function(err, collection) {
        if (!err) {
            callback(null, collection);
        } else {
            console.log("getcollection error: " + err);
            callback(err);
        }
    });
};

Answer №2

If you're looking for a potential solution, consider the following approach:

website


let _database = null;

MongoClient.connect('mongodb://localhost:27017/mydatabasename', (err, db) => {
    _database = db;
});

app.use(function(req, res, next) {
    res.locals.db = _database;
    next();
});
...

routes/main.js


...
router.get('/', function(req, res) {
    res.locals.db; //Utilize the database connection here
});
...

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Utilize Google's Places Direction API Autocomplete feature to pre-select the starting location

I am currently utilizing draggable markers along with 2 autocompletes to assist with obtaining directions. You can find more information about this setup here: https://developers.google.com/maps/documentation/javascript/examples/directions-draggable. With ...

The attempt to compress the code in the file from './node_modules/num2persian' using num2persian was unsuccessful

I have been using the num2persian library to convert numbers into Persian characters. However, whenever I run the command npm run build, I encounter the following error: An error occurred while trying to minimize the code in this file: ./node_modules/num ...

What is the best way to incorporate a <li> view cap within a div element using JavaScript?

Currently, I am attempting to implement a dynamic <li> view limit within the content of a div. My goal is to display only 3 <li> elements each time the div content is scrolled. Although not confirmed, I believe this example may be helpful: ...

Leveraging the power of jQuery to capture and recycle a dynamically generated date

Using a jQuery plugin, a list of dates is generated. Implementing moment.js works perfectly fine as shown in this fiddle (http://jsfiddle.net/UJ9z4/). However, when attempting to apply it to the live file with the plugin running, an undefined error is enc ...

What is the best way to receive a single response for various API endpoints?

I need to retrieve a single response from an API that has multiple page URLs. How can I accomplish this with just one API call? Here is my code: async function fetchArray () { // Fetch `urlArray` from object parameter let urlArray = []; ...

The HTML was generated without any styling properties assigned

After running my script on a galaxy tab, I encountered a strange issue. I created an HTML element (div) and attempted to access the style attribute, only to receive an error message indicating that style is null. Below is the code snippet: var newDiv = d ...

What is the best way to have a button activate a file input when onChange in a React application?

Having an input field of file type that doesn't allow changing the value attribute and looks unattractive, I replaced it with a button. Now, I need the button to trigger the input file upon clicking. How can this be achieved in React? Edit: The butto ...

React Native can trigger a press event, as long as it is not within

My situation involves triggering an action when clicking on the parent component (TouchableOpacity, for example), but not triggering anything when clicking on the children components (Screen and others). It's similar to preventing bubbling on the web. ...

What impact do include statements have on performance?

As I develop a node server, utilizing express and ejs as the templating engine, I've noticed that some of my .ejs files contain 7 to 8 include statements for nested partials. I'm curious whether this approach is resource-intensive or if it won&ap ...

The accuracy of getBoundingClientRect in calculating the width of table cells (td)

Currently, I am tackling a feature that necessitates me to specify the CSS width in pixels for each td element of a table upon clicking a button. My approach involves using getBoundingClientRect to compute the td width and retrieving the value in pixels (e ...

Strategies for distributing a Node.js application across multiple machines

Currently, I am utilizing Express js along with Node-cluster to take advantage of clustering. Additionally, I have implemented PM2 for efficient process and memory management on my single machine setup. However, as my machine only has 2 cores, I am looking ...

Eliminating the table header in the absence of any rows

I have successfully implemented a Bootstrap table in my React application, where users can add or delete rows by clicking on specific buttons. However, I want to hide the table header when there are no rows present in the table. Can anyone guide me on how ...

retrieve data bytes from socket event in Node.js

I'm facing a unique challenge that requires me to implement my own custom TLS solution. The server I need to connect to does not fully comply with the TLSv1.2 specification - it generates client_random and server_random from timestamps, and mandates t ...

Automate CSS slideshow playback using JavaScript

Using only CSS, I created a basic slideshow where the margin of the element changes upon radio button click to display the desired slide. You can view the functionality in the code snippet below. Additionally, I implemented auto play for this slideshow usi ...

React Native - Script for Clearing AsyncStorage

As I work on developing a react native app that relies on async storage, I have implemented conditionals within the components to determine whether API requests should be made or if data stored in memory should be used. To test these conditionals, I find m ...

What steps can be taken to grant a user of an application restricted access to an S3 resource?

Each individual user possesses distinct data stored in S3. This particular resource should be exclusively accessible to the specific user it belongs to. The conventional approach involves retrieving this information on the backend and then transmitting i ...

What is the best approach to concurrently update a single array from multiple functions?

In my React app, I have a form with various input fields and checkboxes. Before making an API call to submit the data, I have functions set up to check if any fields are left blank or unchecked. These check functions are triggered when the form button is ...

Launching a Phonegap app using Node.js and Express framework

My goal is to transform my current webapp into a mobile app. The existing setup consists of a nodejs-express REST API server with an HTML/JS client. I aim to utilize the API from the REST server and replace the client with a phonegap/cordova based mobile ...

Is there a way to immobilize an object in JavaScript without resorting to Object.freeze()?

Is there a way to freeze the following object without relying on Object.freeze()? Let's find out: const obj = { a:'test', b:'Something' } ...

Executing npx triggers a node version that is not currently installed on my system

When attempting to execute the command npx create-react-app my-app, I encountered the following error: Error @typescript-eslint/[email protected]: The engine "node" is incompatible with this module. Expected version "^10.12.0 || >=12.0.0". Got "11.13.0" ...