Heroku + mongoose connection error: no primary server found in set - node.js

I have a mongodb replica set on mongolab.
I'm using nodejs + mongoose. When I'm trying to connect from my local machine everything goes ok.
But after deployment to heroku something wrong happens and mongoose got strange error:
[Error: no primary server found in set]
Here some code (server.js):
async.series([
function(callback){
console.log('DB Connection: ' + siteConf.mongo_url);
mongoose.connect(siteConf.mongo_url, siteConf.mongo_options, callback);
},
function(callback){
http.createServer(app).listen(siteConf.port, callback);
}
],
function(err, results){
if (err) {
console.log(err);
}
console.log('Running in ' + (process.env.NODE_ENV || 'development') + ' mode # ' + siteConf.uri);
}
);
This url I'm using as connection string:
mongodb://username:password#someid-a0.mongolab.com:39897/pm_prod,mongodb://someid-a1.mongolab.com:39897
The main thing I can't understand is: what is the differences between my maching and heroku cloud hosting.
I already tried to remove node_modules and npm install them to be sure that I have same versions as on heroku. (Because heroku do this on each deploy).
Thanks, and sorry for my bad english

This may be a URI problem. The format for DB URIs is:
mongodb://<user>:<pass>#host:port,host:port,...,host:port/db_name
That means that
mongodb://username:password#someid-a0.mongolab.com:39897/pm_prod,mongodb://someid-a1.mongolab.com:39897
should be:
mongodb://username:password#someid-a0.mongolab.com:39897,someid-a1.mongolab.com:39897/pm_prod
It's also worth noting for others: If you are using Heroku's MongoLab add-on, your URI is available as an environment variable at process.env.MONGOLAB_URI, so you don't have to place the URI in your code.
This could also be related to a running question about connectivity between Heroku and Mongo. See https://github.com/jcottr/temps-mort, which references two tickets for the Node Mongo driver:
https://jira.mongodb.org/browse/NODE-4
https://jira.mongodb.org/browse/NODE-5

Related

How to publish a API project with heroku?

I try to publish an API application with Heroku but I am getting an error. What could be the reason? I might be doing something missing. Can you show me what I'm missing?
heroku logs --tail Result
Application index
edit:
I dont have your code snippet so i'm just giving my example here for local development and heroku setup both
In local development
install dotenv npm package
create .env file in root directory and set MONGOURI='Your mongo string here'
then you can import dotenv package in root as shown in below example and use variable as process.env.MONGOURI
On Heroku
there are multiple ways you can do same thing as above which are listed here in config vars. More specifically i'll suggest you to do this way from heroku frontend
require('dotenv').config(); // <-- install `dotenv` package
const MongoClient = require('mongodb').MongoClient;
const mongoUrl = process.env.MONGOURI;
// Connect to the db
MongoClient.connect(mongoUrl, function (err, db) {
if(err) throw err;
db.open(function(err, mongoClient) {
console.log("mongo connected");
});
db.close();
});
I had created a node with mongo boilerplate project to get me started you can check if you want node-auth-mongo

Authentication problem with connecting to mongodb Atlas

What I want to accomplish is probably the simplest thing ever. I just want to connect to mongodb atlas free tier M0 in nodejs using mongodb driver. I already have created a free account and cluster.
Here is my simple code:
const mongoclient = require('mongodb').MongoClient;
const URI = 'mongodb+srv://mohammed:mypassword#lebran-0qf7m.gcp.mongodb.net/test?retryWrites=true';
mongoclient.connect(URI, { useNewUrlParser: true }, (err, client) => {
if(err) throw err;
console.log('mongodb connected');
db = client.db('mern');
})
Here is what happens when I run the file:
Mohammeds-MacBook-Pro:mern ahmed$ node server.js
/Users/ahmed/Projects/mern/server.js:13
if(err) throw err;
^
Error: queryTxt ESERVFAIL lebran-0qf7m.gcp.mongodb.net
at QueryReqWrap.onresolve [as oncomplete] (dns.js:199:19)
I also tried mongo shell with the following command:
mongo "mongodb+srv://lebran-0qf7m.gcp.mongodb.net/mern" --username mohammed
here is the output I get:
MongoDB shell version v4.0.6
Enter password:
connecting to: mongodb://lebran-shard-00-00-0qf7m.gcp.mongodb.net.:27017,lebran-shard-00-01-0qf7m.gcp.mongodb.net.:27017,lebran-shard-00-02-0qf7m.gcp.mongodb.net.:27017/mern?gssapiServiceName=mongodb&ssl=true
2019-02-20T22:48:57.232+0300 E QUERY [js] Error: Authentication failed. :
connect#src/mongo/shell/mongo.js:343:13
#(connect):1:6
exception: connect failed
I am sure I enter my password right. I have changed several ones and none of them work. I have my IP listed as white list. I also have an admin account. All the prerequisites I can think of.
I am able to connect to the local server but not to the Atlas. This really beginning to drive me crazy.
Any help is greatly appreciated...
**UPDATE:
I just deployed my app to heroku and you know what? It connects!! I could not get it to connect using my computer though. So probably it has to do something with my location or my connection, probably the location.

mongoose not connecting to localhost

I seem to have issues when trying to create a mongoose connection. I am following a book published in 2014 so my immediate response was to check the mongoose docs but they agree that the book gives the correct format. Below is my connection:
var dbURI = 'mongodb://localhost/Loc8r';
mongoose.connect(dbURI);
As soon as I add these lines, I get the following error:
Mongoose connection error: mongodb://127.0.0.1/Loc8r
(node:743) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): MongoNetworkError: failed to connect to server [127.0.0.1:27017] on first connect [MongoNetworkError: connect ECONNREFUSED 127.0.0.1:27017]
(node:743) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
If I remove the connection, I have no errors...but that would defeat the purpose of trying to connect to a DB. I also tried substituting localhost in the URI for 127.0.0.1 which is known to solve some issues but I had no luck there either. I am running the localhost on a simple $nodemon command via terminal and nothing else.
Useful info:
MongoDB v3.6.3
Mongoose v5.0.10
Express v4.15.5
Node v8.9.4
Help would be appreciated.
Thanks.
try this way
var MongoClient = require('mongodb').MongoClient
, assert = require('assert');
// Connection URL
var url = 'mongodb://localhost:27017/myproject';
// Use connect method to connect to the server
MongoClient.connect(url, function(err, db) {
assert.equal(null, err);
console.log("Connected successfully to server");
db.close();
});
You are going on the right path but you forgot to put the port on which MongoDB runs,
MongoDB runs on the port 27017
Do not forget to start MongoDB server, If you are on mac open terminal and enter mongod and it will start your MongoDB server then run your code it will work fine.
var dbURI = 'mongodb://localhost:27017/Loc8r';
mongoose.connect(dbURI);
mongoose.connection.on("connected", () => {
console.log("Connected to database");
});
mongoose.connection.on("error", (err) => {
console.log("Database error:" + err);
});
I apologise for this as I was able to find the solution myself but I guess this may help others some day.
The fault lay with the fact that I only installed MongoDB via Homebrew and I stopped as soon as MongoDB was literally "installed" and considered MongoDB to be "installed". I went back to look at how MongoDB should properly be installed and I noticed that I did not make the directory /data/db and give it its permissions which was an important step.
Once I did this, I ran mongod globally, and nodemon on a separate terminal, locally at the root of the app and it worked completely fine and got a successful message in the console. Every time I tried to connect, it was searching for /data/db which it obviously could not find as I had not made it. But I would not have came to this conclusion if Nikhil had not mentioned running mongod.
To summarise, ensure you follow all installing steps in future.

connecting node js to postgresql on heroku

I have deployed my app on heroku and was able to make a connection to the database from pg:psql in my terminal by copying and pasting the code provided by heroku. Now i want to directly connect my node app to postgres on heroku but no success. I followed the instruction on heroku on how to connect nodejs to postgres here.. https://devcenter.heroku.com/articles/heroku-postgresql#connecting-in-node-js but i can't seem to get it to work. I simply installed pg module and pasted the block of code provided by heroku inside my get request in my server.js file.
app.use(express.static('public'));
app.use(bodyParser.json());
app.get('/food', function(req, res) {
pg.defaults.ssl = true;
pg.connect(process.env.DATABASE_URL, function(err, client) {
if (err) throw err;
console.log('Connected to postgres! Getting schemas...');
client.query('SELECT table_schema,table_name FROM information_schema.tables;').on('row', function(row) {
console.log(JSON.stringify(row));
});
});
});
http.listen(process.env.PORT || 3000, function(){
console.log('listening to port 3000!');
});
the error i get from heroku logs is..
/appserver.js:53
if (err) throw err;
Error: connect ECONNREFUSED 127.0.0.0.1:5432
after searching for that error message, i get some people suggesting on fixing or changing the DATABASE_URL. How and where do i change it? I'm lost. I would really appreciated if i can get some help to fix it.
The pg connection is using the database url in your environment:
pg.connect(process.env.DATABASE_URL, function(err, client) {}
Because the DATABASE_URL env variable is not set, it defaults to localhost 127.0.0.0.1:5432. You can set DATABASE_URL in your bashrc or bash_profile. You can name it more specifically PROJECTNAME_DATABASE_URL if you have multiple apps. On Heroku, you can set it like this:
$ heroku config:set DATABASE_URL=postgres://user:password#host:port/database

Cannot connect to mongo on heroku due to missing replicaset parameter

I have a node.js app running on heroku. I am trying to update my mongodb module to "~2.0.3". In my local dev. environment everything is working fine. However, when I deploy the to Heroku I get a "replicaSet parameter must be set" error which did not fire with earlier version of the mongodb module. I am not how to go about it. In particular, I have no idea where can I find the name of that replicaSet.
Here's a transcript of a node REPL session showing the problem:
$ heroku run node --app my-app
Running `node` attached to terminal... up, run.8299
>var mongo = require('mongodb');
undefined
> var a = {}
undefined
> process.env.MONGOLAB_URI
'mongodb://UUUUU:PPPPP.mongolab.com:45970/heroku_appNNNNNNN'
> mongo.MongoClient.connect(process.env.MONGOLAB_URI, function (err, db) {
a.err = err; a.db = db; console.log('CALLED'); });
undefined
> CALLED
undefined
> a
{ err:
{ [MongoError: replicaSet parameter must be set]
name: 'MongoError',
message: 'replicaSet parameter must be set' },
db: null }
>
One more thing: when I access the DB through the web interface I see only two system collections: system.indexes and system.users. To the best of my understanding this suggests that my DB is not part of a replicaSet which makes the whole thing weird.
This is indeed a problem in 2.0.3. It was solved in 2.0.4 by this pull request.
Bottom line: If you encounter "replicaSet parameter must be set" error in 2.0.3, upgrade to 2.0.4.

Resources