Mongoose : Failed to connect to mongodb instance, but mongo works fine - mongodb

I'm facing a quite odd issue today.
I have a MongoDB database working just fine on a remote server, say 1.2.3.4, running on port 22222.
When I use the mongo cli to connect via the command line interface, everything works as expected:
mongo --host=1.2.3.4 --port=22222
But when I try to connect to the same instance using mongoose:
var options = {
server: {},
replset: {}
};
options.server.socketOptions = options.replset.socketOptions = { keepAlive: 120 };
mongoose.connect('mongodb://1.2.3.4:22222/test', options);
I get this error:
failed to connect to server [1.2.3.4:22222] on first connect
Anybody knows why?
FYI the all setup is in my company, which happens to have a corporate proxy.
I was thinking that maybe the proxy was the evil one in this case, but then why the mongo cli connection is working just fine?

Do you have a db called test? And have you tried omitting the options?
i.e. mongoose.connect('mongodb://1.2.3.4:22222/test');

Related

Mongodb not authenticating on localhost or connecting authenticated mongodb compas

System
Hi I am running mongodb on ubuntu 20.14.
Im running mongodb with systemctl
What I've done
I've tried to make it more secure by adding an admin user and enabled authentication.
Ive restarted the service multiple times.
config file:
security:
authorization: enabled
How I created user:
use admin
db.createUser({
user: "username",
pwd: "123456",
roles:["root"]
})
Problem
I am still able to connect through mongodb compass without any auth??? Im able to do everything even tho I enabled the authentication?
I am not able to login authenticated using these urls:
mongodb://username:password#localhost:27017/
mongodb://username:password#localhost:27017?authSource=admin
Im sure the config file is loading since authentication works in console and I can see the right config load in the mongod.log
It would be this one:
mongodb://username:password#localhost:27017?authSource=admin
See also: Authentication failure while trying to save to mongodb
Yes, even without authentication you can connect to Mongo database in any case. However, apart from harmless commands like db.help(), db.version(), db.getMongo(), etc. you cannot execute anything.
You can skip parameter enableLocalhostAuthBypass. The localhost exception applies only when there are no users created in the MongoDB instance.
Solution
I thought the issue was with mongodb compass.
So what I did was deleting the application and when I did that I saw that I had mongodb installed on my pc too.
I was never connecting to the mongodb that I have created on my ubuntu server but on my own pc.

Deno not connecting to mongodb

I'm hosting a test database on mongodb atlas, and I'm trying to connect via a simple deno app, but I keep getting the following error:
failed to lookup address information: Temporary failure in name resolution
I have made sure nothing is blocked in my firewall, and flushed my DNS to make sure it wasn't that. My code is below.
const URI = 'mongodb+srv://testUser:*password*#testdb.byjzd.azure.mongodb.net/TestDB?retryWrites=true&w=majority';
const client = new MongoClient();
await client.connect(URI).catch((err: string) => {
console.log(err);
});
Note: connecting a simple NodeJS app works fine.

node pg.connect never calling its callback, how to debug?

So I have a working express server talking to a postgres backend running on a heroku server. I'm trying to move to AWS. On AWS I think I have everything set up correctly. I have my express server running (under PM2 though that shouldn't make a difference. I can SSH into the ec2 and from there launch a psql and connect to the DB without any issues, I've created my schema no problem.
However my app is not working with the DB, Most likely its not even connecting but I'm getting nothing back. not even a timeout. I first tried with env variables to set everything up but decided to put the user/password in the code.
my express code looks like this obviously i changed the values for the post but they are the same values
I use on the psql command line
const {Client} = require('pg');
const db = new Client({
user: 'myUserName',
host: 'myHostName',
password: 'myPassword',
});
console.log("about to connect to the DB");
db.connect(err => {
if (err) {
console.error('connection error', err.stack)
} else {
console.log('connected')
}
}
);
In my logs I get the line "about to connect to the DB" but I never get anything else I do not
get the error nor the success line.
how do I see what's wrong? with no feedback I'm stuck. Is there something I can check in aws?
I doubt its a security group issue since psql works
Seems I had a bad version/installation of Node. I created a new instance on AWS and installed Node 12.x instead of "latest" which was 14.x and its working fine now.

Meteor database connection

I am trying to connect to my Mongo database which is situated on the machine as my Meteor app. Here are two files in my app:
a.js:
if (Meteor.isServer) {
var database = new MongoInternals.RemoteCollectionDriver("mongodb://127.0.0.1:3001/meteor");
Boxes = new Mongo.Collection("boxes", { _driver: database });
Meteor.publish('boxes', function() {
return Boxes.find();
});
}
b.js:
if (Meteor.isClient) {
Meteor.subscribe('boxes');
Template.homeCanvasTpl.helpers({
boxes: function () {
return Boxes.find({});
}
});
}
But I keep getting a "Exception in template helper: ReferenceError: Boxes is not defined" error - any ideas?
How can you connect to a MongoDB with Meteor?
Scenario A: Use the built-in DB as default
This is much simpler than what you did. When you run meteor you actually start a DB with the Meteor server, where Meteor listens on port 3000 and the database on port 3001. The Meteor app is already connected to this database at port 3001 and uses a db named meteor. There is no need whatsoever to fall back to MongoInternals.RemoteCollectionDriver. Just remove that code and change things to:
Boxes = new Mongo.Collection("boxes"); // use default MongoDB connection
Scenario B: Use a different DB as default
Using the MONGO_URL environment variable you can set the connection string to a MongoDB when starting the Meteor server. Instead of the local port 3001 database or an unauthenticated connection you can specify exactly where and how to connect. Start your Meteor server like this:
$ MONGO_URL=mongodb://user:password#localhost:27017/meteor meteor
You can also leave out the user:password# part of the command if no authentication is needed.
Scenario C: Connect to a second (3rd, etc) DB from the same Meteor app
Now we need to use MongoInternals.RemoteCollectionDriver. If you wish to use another database that is not the default DB defined upon starting the Meteor server you should use your approach.
var database = new MongoInternals.RemoteCollectionDriver('mongodb://user:password#localhost:27017/meteor');
var numberOfDocs = database.open('boxes').find().count();
Bonus: Why should you not use MongoInternals with Mongo.Collection?
As the docs indicate you should not pass any Mongo connection to the new Mongo.Collection() command, but only a connection to another Meteor instance. That means, if you use DDP.connect to connect to a different server you can use your code - but you shouldn't mix the MongoInternals with Mongo.Collection - they don't work well together.
Based on feedback from saimeunt in the comments above, s/he pointed out that MongoInternals is unavailable to the client portion of a Meteor app. Therefore, the solution was to add in the line "Boxes = new Mongo.Collection("boxes");" to the client logic - here was the final working solution:
a.js:
if (Meteor.isServer) {
var database = new MongoInternals.RemoteCollectionDriver("mongodb://127.0.0.1:3001/meteor");
Boxes = new Mongo.Collection("boxes", { _driver: database });
Meteor.publish('boxes', function() {
return Boxes.find();
});
}
b.js
if (Meteor.isClient) {
Boxes = new Mongo.Collection("boxes");
Meteor.subscribe('boxes');
Template.homeCanvasTpl.helpers({
boxes: function () {
return Boxes.find({});
}
});
}
Meteor has 2 different environment : the server environment running on Node.JS and the client environment running in browsers.
In your code you declare the Boxes Mongo collection only in the server environment, you need to take this declaration out of the Meteor.isServer condition (and BTW don't use these, separate your code in server/, client/ and lib/ directories).
Also, not sure if you need to connect to your MongoDB this way, maybe you should look into the MONGO_URL environment variable it probably already does what you need ? (provide a mongo connection URL to a distant (or local) Mongo server).

NodeJS, ExpressJS & PassportJS Sessions on Cloud9 connecting to Appfog Mongo

I'm having great difficulty getting any sort of connection to MongoDB on Appfog for session storage working. I'm currently running Node Express with PassportJS and Mongoose. I've followed numerous examples and tutorials online and tried a few ODM mappers.
I must confess, I've struggled to get any sort of connection let alone, the abstracted sessions stuff working.
I've tried the SO examples here and here without success. Everytime I attempt to connect with the following code:-
var env = process.env.NODE_ENV || 'development',
config = require('./config/config')[env],
auth = require('./config/middlewares/authorization'),
mongoose = require('mongoose');
// Bootstrap db connection
mongoose.connect(config.db);
I get a:-
Error: Error setting TTL index on collection : sessions
at module.exports._get_collection (/var/lib/stickshift/514a22705973cafc85000110/app-root/data/447240/node_modules/connect-mongo/lib/connect-mongo.js:137:23)
at Db.ensureIndex (/var/lib/stickshift/514a22705973cafc85000110/app-root/data/447240/node_modules/mongodb/lib/mongodb/db.js:1227:28)
at Db.indexInformation (/var/lib/stickshift/514a22705973cafc85000110/app-root/data/447240/node_modules/mongodb/lib/mongodb/db.js:1371:30)
Can anyone offer any possible direction or help to get this working please?
Please ask if you need further dumps of the code here to aid a solution.
Help appreciated.
I had the same problem and it happened because I was using a partially connected db to initialize express.session().
This is what I had initially:
mongoose.connect(dbPath);
...
app.configure(function() {
...
app.use(express.session({
secret : secret,
store: new MongoStore({ db: mongoose.connection.db })
}));
...
});
The 'new MongoStore()' call happens before mongoose.connect() finishes so it uses the not-yet-connected db to set the TTL for 'sessions' and fails. I switched to "new MongoStore({ url: dbPath })" and that fixes the issue but probably results in 2 different db connections.
I was getting the same error, got past it by using the code in this question to get more error info dumped out; it helped me realize that the problem really was my user Id and password in the connect string.
I couldn't get the connection to AppFog to work. Unfortunately, AppFog themselves were unhelpful also. Therefore, I spun up a MongoHQ instance and no problems connecting at all.