MongooseServerSelectionError: connect ETIMEDOUT - javascript

I recently ran into this problem. When I try to run my Node.js app, I get this error MongooseServerSelectionError: connect ETIMEDOUT. It also said type: 'ReplicaSetNoPrimary'. For the past few months it was working perfectly and I had never got this error. I am using MongoDB Atlas for the database and Mongoose for its driver. I am using the latest version of Mongoose.
Here is my app.ts:
const CONNECTION_URL = "mongodb+srv://name:<password>#cluster0.vyegx.mongodb.net/MyApp?retryWrites=true&w=majority"
mongoose.connect(CONNECTION_URL).then(_INIT_)
async function _INIT_(){
const server = app.listen(PORT, ()=>{
console.log("listening on port "+PORT+"...")
});
const io = new Server(server);
}
I have tried to whitelist my ip, but it's not working.
UPDATE It works perfectly with no errors in Heroku but when I try to run it from my computer it gives an error.

need to set useUnifiedTopology: false

Related

"Where" are Websocket servers hosted on Heroku?

I'm trying to host a Websocket server on my heroku app. There already is a GraphQL server running, but I don't think it's the cause of my problem.
So my server is started like this
const wss = new ws.Server({ port: port }, () => console.log(`Serveur WebSocket prĂȘt ${port}`));
There is no error, but when I try to connect to the server in my browser, just like this :
const ws = new WebSocket('wss://ethyme-api.herokuapp.com/');
I get an error 404.
So my question is, what is the path of the ws server, so I can connect to it ?
Thanks
If your Heroku app is called ethyme-api and and your locally run application is available under ws://localhost:$PORT/ the websocket will be available under wss://ethyme-api.herokuapp.com/ and ws://ethyme-api.herokuapp.com/

How to determine if Express app's connection to MongoDB is really open?

I'm working on an Angular 7 app with MongoDB, Node and Express. If I start my Express app (using npm start command) before connecting to MongoDB (with mongod command), the Express app first throws an error because it's unable to establish connection with MongoDB. Once MongoDB is up and running, the Express app informs me that MongoDB is now connected at port 27017. However, any http post requests I execute through my Angular app cause Express to return a 200 status code (which tells me everything is ok), but MongoDB fails to create a document as a result of the http post request. How do I make sure that MongoDB is not only connected but that the connection can successfully create the new document when I execute the post http request? I read somewhere that MongoDB's ability to save/create a document requires it to have an open connection. In that regard, what's the difference between having an open connection and MongoDB being connected at port 27017?
Here's the code I use in my Express app.js file 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 is necessary to have, considering I already have 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);
})
Here's the npm log, showing the connection error at first, followed by successful connection, followed by several Post requests with status code 200, yet nothing got 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
Of course, this problem was resolved when I restarted my express app after an active mongoDB session, but I won't always have the luxury of inspecting logs and the app's ability to create documents when in production. Appreciate some guidance.
You have to connect to mongo first, then initialize express.
mongoose.connection.on('connected', ()=>{
console.log('MongoDB connected at port 27017');
app = express();
});
//once open event is not necessary
After that, you can consider writing init functions that all return promises. Like that you can chain it and all is clear. Here is an example where rabbit, then mongo, then express is inited.
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))

react + mongodb port

I'm trying to build react app with mongoDB. React app is running on port 3000
and when i'm running server.js for mongodb on the same port, my app is overriten.
How do I make mongoDB to run on same port?
Thanks
You can't run the web server and database on the same port. The convention is to use the next port, ie 3001 for Mongo.
It doesn't actually matter which port Mongo runs on, as long as your app knows about it
UPDATE
Run mongo with a command like this:
mongod --dbpath=/home/me/mydata --port 3001
If you are using npm package mongodb, connect like this
var MongoClient = require('mongodb').MongoClient
, assert = require('assert');
// Connection URL
var url = 'mongodb://localhost:3001/myproject';
// Use connect method to connect to the Server
MongoClient.connect(url, function(err, db) {
assert.equal(null, err);
console.log("Connected correctly to server");
db.close();
});

No connection events are being fired - Mongoose 4.7.1 & Express

I am having issues connecting my express app to MongoDB via Mongoose. There is no complicated set up, its fairly basic:
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/homeApp');
var db = mongoose.connection;
db.on("connecting", function(){
console.log("Connecting to DB...");
});
db.on('connected', function(){
console.log('Connected to db');
});
db.on('error', function(error){
console.log('Error');
});
Simple enough, right? But none of these events are being fired. Mongo is running ok and it's on the default port. I have also tried changing localhost to 127.0.0.1 and checked the contents of my etc/hosts file and all seems ok. If I mangle the URI string to something like:
'mongoldb://lclhost/homeApp'
I get an error saying it cannot connect, which is to be expected so it seems like a connection is being made/attempted but nothing is happening.
I've logged the contents of db.Db to the console and noticed this connected: false, which suggests it's not even attempting a connect?
Any ideas? This is Mongoose 4.7.1 running on macOS Sierra 10.12.5.
Thanks in advance!
Figured it! I tried using the mongodb client without mongoose and everything worked as expected, so I knew the connection was ok and that left the blame with mongoose.
Turns out I was not using 4.7.1 as I had thought, and that just running npm install mongoose --save had in fact installed version 3.x, which is not compatible with the latest version of MongoDB according to the Mongoose docs. http://mongoosejs.com/docs/compatibility.html
Upgrading the version number in my package.json file to 4.7.1 fixed the issue.
the mongoose.connect method takes in a callback, which you could use to check the connection:
mongoose.connect(uri, options, function(error) {
// Check error in initial connection.
if (error) {
console.log(error);
} else {
console.log('connected ok');
}
});
I think your connection is being created, but your db.on events are not being triggered.

Express server basic example not working

I have node v7.4.0 installed on my remote server. I've installed the latest version of express which is 4.14.0 and I've set up index.js in my public_html. index.js is a copy of the official test online:
const express = require('express')
const app = express()
const port = 3000
app.get('/', (request, response) => {
response.send('Hello from Express!')
})
app.listen(port, (err) => {
if (err) {
return console.log('something bad happened', err)
}
console.log(`server is listening on ${port}`)
})
When I run node index.js while in public_html, I get the expected results: server is listening on 3000. When I go to my server's domain name address or IP address on port 3000, I just get that it is "Connecting" and then it fails saying it took too long to respond (plus no response in the command line). What can I look into to fix this?
Looks like nothing is wrong with your code. It may be a firewall/antivirus; additionally, Try using another browser like Firefox. Make sure to use the loopback ip 127.0.0.1:3000 or localhost:3000 (same thing).
For me, it was because of the proxy. After disabling proxy for intranet, it worked fine.
For me it was because of the firewall settings. I added private network access and then it worked fine.

Categories

Resources