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

Create a structure of connected nodes by parsing a plain text string

My input is a string with annotations and data: var string = "@anno1[ data1 xyz @anno2[data2 @anno3[data3] data4] data5 @anno4[data6] data7]" I want to transform this string into an object with structured information: var childs = [ { ...

Vue Material - Effortlessly integrate native transitions within router views

In the project I'm currently working on, I have chosen to use Vue Material for the development of a single-page application. The approach I am taking follows a common trend in which a central "container" component is utilized to manage the shifting vi ...

MERN stack tutorial: How to modify a particular string in an array's object

When it comes to connecting my backend (Express) server to the database using mongoose, I am facing an issue with performing CRUD operations. While I can easily access and update direct data in objects, I need a solution to manipulate array data as well. ...

Having trouble establishing a connection to the FTP server through the "ftp" package provided by npm

Attempting to establish a connection to a Secured FTP server using the "ftp" package. When connecting to an unsecured server, everything functions as expected with all events firing and content being displayed. However, upon trying to connect to a server ...

A particular character is displayed exclusively in a text box using either jQuery or JavaScript

Text Box <input id="txtbo" type="text" value="CAN'T TOUCH THIS!" size="50" /> Solution Using jQuery or Javascript: var readOnlyLength = $('#txtbo').val().length; $('#txtbo').on('keypress, keydown', function(even ...

Select an image based on the input value provided

I'm new to coding and I'm attempting to replicate the search functionality of icomoon where typing a word displays related images. However, I'm facing an issue where I can't seem to get the value entered in the input field to trigger an ...

How can I execute JavaScript code within Aptana Studio 3 IDE?

After creating a Test.js file, I added two lines of JavaScript code: var x = 5; console.log("The answer is: " + x); The desired output would be: "The answer is: 5" I am curious if there's a way to view this outcome in the Aptana Scripting console, ...

How can I access dynamically created input elements without using $refs, such as getting focus?

Is there a way to handle dynamically created inputs for editing purposes without using jQuery or vanilla JS all the time? Each input element has its own ID and is displayed through v-if when editing is triggered. However, Vue does not recognize them in r ...

Is it possible to request a GET on a server's JSON file using a specific key?

I am currently working on a project involving an auto-suggestion exercise using a JSON file located on a server. I'm not entirely clear on the web development terminology, so one requirement has me a bit confused: The requirement states: "On the keyu ...

Implementing CloudFront to accelerate NodeJS Express application

I am facing an issue with my application that serves dynamic HTML and static files using NodeJS/Express. I recently deployed an AWS CloudFront distribution in front of it, but I'm encountering a problem where only the HTML content is being served whil ...

Is it possible to send requests to multiple APIs using a TypeScript event handler?

I'm facing a challenge in pinging multiple APIs within a single function. It seems like it should be possible, especially since each API shares the same headers and observable. I attempted to write a function for this purpose, but unfortunately, it do ...

Switching carousel background image upon navigation click

I am currently working with a Bootstrap Carousel and I want to customize the background (an image) for each slide. I have 4 slides in total, each corresponding to a specific background image. <!DOCTYPE html> <html lang="en" dir="ltr ...

AngularJS: Initiate a Bootstrap modal upon webpage loading

As I work on designing a web application using AngularJS, I aim to implement the launching of a bootstrap modal upon page load through AngularJS. Here is the structure of my modal: <div class="modal hide fade" id="myModal"> <div class="moda ...

Update information with a fresh GET call - React Dropdown

I have implemented a Dropdown Menu using MUI that allows users to select a specific day value. I would like the menu to trigger a new GET request with the updated parameter whenever the selection changes. However, I am unsure how to achieve this since it u ...

Is there an issue with this particular post request?

Here is the code I wrote to validate whether a POST request can be inserted into a database. When I send a Postman request with the following details: localhost:8080/api/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="cdb8bea8b ...

Why does Froala Editor not maintain formatting when retrieving data from the database?

I've been using the Froala editor to add content on my website, and it's doing well for inserting data into the database. However, I'm facing an issue when retrieving data from the database as it doesn't maintain the original formatting ...

Tips on customizing the appearance of two Material-UI Sliders across separate components

Looking to customize two sliders, each within their own react component. Slider in the first component const customizedThemeSlider1 = createTheme({ overrides:{ MuiSlider: { thumb:{ color: "#4442a9", marg ...

Node.js routing currently lacks the ability to easily verify the presence of a JWT token for every route

I have a node application where, upon routing to ('/login') with valid credentials, I generate a JWT token with an expiry time and direct the user to the next page. If the user tries to access any other route directly (e.g., '/home') af ...

Using jQuery's .load() function to exclusively receive image bytecodes

I am utilizing jQuery's .load() function to receive the bytecode of loaded images. Could it be due to a lack of specified MIMEType? because I'm using an image URL without a file extension? necessary to wrap the entire operation somehow? Here& ...

Utilize JSON data in d3.js for creating a scatterplot visualization

I have recently started working with d3.js and I'm facing some challenges. From what I understand, the second parameter passed in d3.json() is used to process data from a JSON file. Here is my code: d3.json(base_url() + "data/data.json", clean_data) ...