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.