Ways to confirm the actual openness of Express app's connection to MongoDB?

I'm currently developing an Angular 7 application that utilizes MongoDB, Node.js, and Express. One issue I encountered is that if I start my Express app (using the npm start command) before connecting to MongoDB (using the mongod command), the Express app throws an error as it fails to establish a connection with MongoDB. Once MongoDB is running, the Express app successfully connects and notifies me that MongoDB is connected on port 27017. However, when I trigger http post requests from my Angular app, even though Express returns a 200 status code indicating success, MongoDB does not create the document as expected. I've come across information suggesting that MongoDB needs an open connection to save or create a document. So, what's the difference between having an open connection and MongoDB being connected at port 27017?

Below is the snippet of code from my Express app.js file used to connect to MongoDB:

var express = require('express');
var mongoose = require('mongoose');

var app = express();

var mongoose_uri = process.env.MONGOOSE_URI || "mongodb://abc:abc123@localhost:27017/databank?authSource=admin";
mongoose.set('debug', true);
mongoose.connect(mongoose_uri);

mongoose.connection.on('connected', ()=>{
  console.log('MongoDB connected at port 27017');
});

//Not sure if the mongoose.connection.once method is essential since I already have the mongoose.connection.on above.

mongoose.connection.once('open', ()=>{
  console.log('MongoDB connection now open');
})
//MongoDB connection error
mongoose.connection.on('error', (err)=>{
  console.log(err);
})

The npm log displays the connection error initially, followed by the successful connection, but despite several Post requests with a status code of 200, no data gets saved to the MongoDB collection.

[nodemon] 1.19.0
[nodemon] to restart at any time, enter `rs`
[nodemon] watching: *.*
[nodemon] starting `node ./bin/www`
API Gateway listening at  http://localhost:8085/api
Web Server listening at  http://localhost:8085/
{ Error: connect ECONNREFUSED 127.0.0.1:27017
    at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1097:14)
  name: 'MongoError',
  message: 'connect ECONNREFUSED 127.0.0.1:27017' }
MongoDB connected at port 27017
POST /api/contactus 200 335.509 ms - 18
POST /api/contactus 200 9.082 ms - 18
POST /api/contactus 200 3.916 ms - 18
POST /api/contactus 200 6.268 ms - 18
POST /api/contactus 200 61.876 ms - 18

I managed to resolve this issue by restarting my express app after a successful MongoDB session. However, in a production environment, I cannot always check logs manually. Any suggestions on how to ensure MongoDB can successfully create documents when receiving http post requests are highly appreciated.

Answer №1

First, establish a connection to MongoDB and then initialize Express.

mongoose.connection.on('connected', ()=>{
  console.log('Successfully connected to MongoDB on port 27017');
  app = express();
});
//The 'open' event listener is not necessary anymore

Next, consider creating initialization functions that return promises for better organization. For example, you can initialize RabbitMQ, followed by MongoDB, and finally Express in a chain.

initRabbit()
    .then(initMongo)
    .then(initExpress)
    .catch(e => {
        error({error:"boot", cause: e})
        process.exit(-1)
    })

const initMongo = () => new Promise(resolve => mongoose.connection.on('connected', resolve))

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

What is the best way to eliminate concealed divs from the view source of a webpage?

On my HTML page, I have some hidden DIVs that can still be viewed in the page source. I want to ensure that these DIVs are not visible to users when they inspect the page source. Is there a way to achieve this using Javascript or another solution? ...

How can labels be added when mapping over JSON data?

If I have JSON data structured like this: { "siteCode": "S01", "modelCode": "M001", "modelDesc": "Desc01", "price": 100 "status": "A", "startDate": "Ma ...

Firefox experiencing issues with the onchange event

Here in this block of code, I have two dropdown lists: one for department and the other for section name. Based on the selected department, I dynamically change the options available for the section name dropdown list and then populate the values from both ...

Steps for resetting the Redux Reducer to its initial state

Is there a way to reset a specific Redux Reducer back to its initial state? I'd like the register reducer's state to revert back to its initial state when leaving the register page, such as navigating to the Home or other pages in a React Nativ ...

Using various jQuery autocomplete features on a single webpage

UPDATE I have observed that the dropdown elements following the initial one are not being populated correctly. .data( 'ui-autocomplete' )._renderItem = function( ul, item ) { return $( "<li></li>" ) .data( "i ...

Comparison between UI Router and ngRoute for building single page applications

Embarking on a new Angular project, a single page app with anticipated complex views such as dialogs, wizards, popups, and loaders. The specific requirements are yet to be clarified. Should I embrace ui.router from the start? Or begin with ngRoute and tra ...

Perform a Node.js GET request following a previous AJAX POST request

Having a major issue with using AJAX... I am not receiving the expected 304 page after a successful AJAX request... here is my code snippet: $.ajax({ url: "/crawling/list", type: "POST", dataType: "json", ca ...

React Router will not remount the component when using this.context.router.push

We have implemented a click handler that utilizes react router 2.0 to update the URL with this.context.router.push(). Here is the code snippet: selectRelatedJob(slug) { JobActionCreators.fetchJobPage(slug); JobsActionCreators.getRelatedJobs({'sl& ...

Managing selected ticket IDs in a table with AngularJS

I have a table that includes options for navigating to the next and previous pages using corresponding buttons. When I trigger actions for moving to the previous or next page (via controller methods), I store the IDs of checked tickets in an array $scope. ...

What is the best way to convert API data into a currency format?

Hello, I need assistance with formatting data retrieved from an API into a currency format. The code below successfully retrieves the data but lacks formatting. For instance, if the data displays as 100000000, I would like it to be formatted as IDR100.000. ...

Showing HTML element when the model count is zero - ASP.NET MVC View

My view has a dynamic element that switches between two options depending on the Model.Count property. Check out the code below: @if (Model.Count() == 0) { <div class="well well-lg"><h3>Everyone is present! No absences today :)</h3>& ...

Express Js EJS Layouts encountered an issue: No default engine was specified and no file extension was included

Hey there! I'm currently experimenting with implementing Express EJS Layouts in my application. However, as soon as I try to include app.use(expressEjsLayouts), an error is being thrown. The application functions perfectly fine without it, but I reall ...

Troubleshooting: Issue with passing parameters in Wordpress ajax function

In my Wordpress Ajax implementation, I am facing an issue where the parameter value metakey: id is not being passed to $_POST["metakey"]. As a result, when I do a var_dump($_POST), it shows array(0) { }. If I manually set a static value for the variable i ...

There seems to be an issue with the next-sitemap image location showing as undefined in the sitemap

I am having an issue with creating a sitemap in image:loc. When I view my xml in the browser, loc is showing as undefined. The goal is to display images present in blogs. Additionally, when I use console.log, the link displays in the terminal but shows as ...

Enhancing the node module of a subpackage within Lerna: A step-by-step guide

I recently integrated lerna into my workflow to streamline the installation of all node modules for multiple sub packages with just one command. Currently, I'm only utilizing the lerna bootstrap feature. Here's a snippet from my lerna.json: { & ...

The sidebar stays fixed in place and doesn't adapt to varying screen resolutions

Check out my website at . I have a fixed, blue sidebar on the left side of the page to ensure its content is always visible. However, I'm facing an issue with smaller resolutions like 1024x768 where some bottom content is cut off. How can I adjust the ...

My webpage is experiencing issues with function calls not functioning as expected

I have created a select menu that is integrated with the Google Font API. To demonstrate how it works, I have set up a working version on JSBIN which you can view here. However, when I tried to replicate the code in an HTML page, I encountered some issues ...

Using a jquery function within a Laravel view

I am trying to retrieve a selected item from a dropdown menu using jQuery and then redirect it to a controller function. This function will return some data to be displayed based on the selected item. I could really use some assistance with this. Here is m ...

Breaking down and modifying JavaScript JSON objects

Can someone explain how to separate a JSON object and make updates based on the ID? I've heard about using stringify! But how do I actually implement the function to update the object? <input type="text" value="{"id":"1","price":"30.00","edit":0}, ...

The jquery datepicker is malfunctioning after switching to another component

My current setup includes the following versions: jQuery: 3.3.1 jQuery UI: 1.12.1 AngularJS: 6 Here's a snippet of my code: <input id="test" type="text" class="form-control" value=""> In my component (component.t ...