mongodb mongoose connection open callback doesnt get called - mongodb

I have a MEAN project and this is a snippet from my server.js
var db = require('./config/db');
// url : 'mongodb://localhost/cdnserver'
// results are same for 127.0.0.1 or the machines ip
console.log(mongoose.connect(db.url));
mongoose.set('debug', true);
mongoose.connection.on('connected', function () {
console.log('Mongoose default connection open to ' + db.url);
});
// If the connection throws an error
mongoose.connection.on('error',function (err) {
console.log('Mongoose default connection error: ' + err);
});
// When the connection is disconnected
mongoose.connection.on('disconnected', function () {
console.log('Mongoose default connection disconnected');
});
This is a setup that has been working well for over 3 months now. Now I am replicating my whole MEAN stack along with database to other machine. I took a mongodump and did mongorestore. The restored db setup looks fine through mongo from terminal.
However, when starting the server, connection-open callback is not getting called. disconnected and error callbacks are getting called if I stop the mongodb service. How do I debug this further?
I am attaching the console output from both the setups.
Setup 1 :
Mongoose {
connections:
[ NativeConnection {
base: [Circular],
collections: {},
models: {},
replica: false,
hosts: null,
host: 'localhost',
port: 27017,
user: undefined,
pass: undefined,
name: 'cdnserver',
options: [Object],
otherDbs: [],
_readyState: 2,
_closeCalled: false,
_hasOpened: false,
_listening: false,
db: [Object] } ],
plugins: [],
models: {},
modelSchemas: {},
options: { pluralization: true } }
Server up on 80
Mongoose default connection open to mongodb://localhost/cdnserver
1
Mongoose: videos.find({}) { skip: 0, limit: 5, fields: undefined }
Setup 2:
Mongoose {
connections:
[ NativeConnection {
base: [Circular],
collections: {},
models: {},
replica: false,
hosts: null,
host: 'localhost',
port: 27017,
user: undefined,
pass: undefined,
name: 'cdnserver',
options: [Object],
otherDbs: [],
_readyState: 2,
_closeCalled: false,
_hasOpened: false,
_listening: false,
db: [Object] } ],
plugins: [],
models: {},
modelSchemas: {},
options: { pluralization: true } }
Server up on 80
1
1
Mongoose default connection disconnected
Mongoose default connection error: Error: connection closed
cat /var/log/mongodb/mongodb.log shows exactly the same output in both the machines.
Update 1: The setup started working properly out of blue and it stopped again. I am not able to figure out what is making this happen.

I figured it out finally, the new setup was using a newer version of nodejs.
When I moved to 6.x from 7.x it worked fine. I guess the mongoose, node 7, mongodb versions didnt go well together.

Related

DENO mongo atlas connection issue when primary cluster is changing

As written in deno.land/x/mongo, to connect to mongo Atlas, such configuration should be use :
import { MongoClient } from "https://deno.land/x/mongo#v0.21.0/mod.ts";
const client1 = new MongoClient();
await client.connect({
db: "<db>",
tls: true,
servers: [
{
host: "<host>",
port: 27017,
},
],
credential: {
username: "<user>",
password: "<password>",
db: "<db>",
mechanism: "SCRAM-SHA-1",
},
});
const db = client1.database("TestingDB");
export default db;
There, <host>should be replaced by a specific cluster address (looks something like that : cluster0.hmdnu.mongodb.net) and not a full string as mongodb+srv://user1:MYPASSWORD#cluster0.hmdnu.mongodb.net/TestingDB?retryWrites=true&w=majority.
This solution works well. But there is, I believe, a downside : Sometimes, a Mongo cluster can fail and a Secondary cluster can become Primary. Has we are using a specific cluster on our code, that cluster might be down and our program as well. Any one encounter a similar issue ? and how did you resolve it ?
Add more cluster
servers: [
{
host: "<host>", /*primary*/
port: 27017,
},
{
host: "<host>", /*secondary*/
port: 27017,
},
{
host: "<host>", /*secondary*/
port: 27017,
},
],

Connect Remote Database on different server with mongoose

I have a requirement where I have to connect two different databases on different remote servers with mongoose from my main server.
Now,I have done a bit of research and founded that we can connect multiple instance with mongoose and then can use useDb() to use the specific database.
Everything works fine when I am connecting it to 2 local database but when the database are remote and I am connecting it via IP it is giving authentication error.
I guess connections are getting mixed.
Below is my code that I am using which is working on local database:
mongoose.connect('mongodb://'+db.host+':'+db.port+'/'+db.dbname,{user: db.username, pass: db.password, useUnifiedTopology: true, useNewUrlParser: true, useCreateIndex: true, useFindAndModify:false })
.then(() => {
console.log(`db connection successful`);
mongoose.connect('mongodb://'+db2.host+':'+db2.port+'/'+db2.dbname,{user: db2.username, pass: db2.password, useUnifiedTopology: true, useNewUrlParser: true, useCreateIndex: true, useFindAndModify:false })
.then(() => console.log(`db connection2 successful`))
.catch((err) => logger.error("db connection2 error", err));
}).catch((err) => logger.error("db connection1 error", err));
When host is localhost everything works fine but when I change it with the IP of the server it throws authentication error.
'not authorized on db to execute command { find: "collection_name", filter: { basicDetails.applicationNumber: "5000" }, projection: {}, returnKey: false, showRecordId: false, lsid: { id: UUID("164bf515-cec6-470f-fewcfrv") }, $clusterTime: { clusterTime: Timestamp(158461230, 1), signature: { hash: BinData(0, 6210C6E1586CFDBDC), keyId: 12346890 } }, $db: "DB" }'

Nuxt.js socket hang up on axios get only on https not http server

I'm using Nuxt 2.8.1, Axios Module (https://axios.nuxtjs.org).
I followed up this guide https://nuxtjs.org/faq/http-proxy/ to solve CORS problems on Firefox/IE, but ended up NuxtServerError: socket hang up on every proxied request if I ENABLE server https option in nuxt.config.js, not if I disable.
I tried adding rejectUnauthorized: false to server https param, wrote an express server to handle the SSL certificate and render using Nuxt,... but still can't solve the problem.
This is my nuxt.config.js:
env: {
API_HOST: 'https://api.mywebsite.com',
BASE_URL: process.env.BASE_URL || 'http://localhost:3000',
},
axios: {
proxy: true,
},
proxy: {
'/api/': {
target: 'https://api.mywebsite.com/api',
pathRewrite: {'/api': ''},
credentials: false,
}
},
server: {
port: 3000,
https: {
rejectUnauthorized: false,
key: fs.readFileSync('../privkey.pem'),
cert: fs.readFileSync('../fullchain.pem')
}
}
It works well if i just remove whole https param in 'server'. Here is my axios call on store/index.js:
export const actions = {
async nuxtServerInit ( { commit } ) {
const { data } = await this.$axios.get('/api/option');
let options = {};
data.forEach(item => {
options[item.Name] = item.Value;
});
commit('setOptions', options)
},
}
This is my console log on that axios call:
Promise { 18:04:38
<rejected> [Error: socket hang up] {
at createHangUpError (_http_client.js:323:15)
at Socket.socketOnEnd (_http_client.js:426:23)
at Socket.emit (events.js:203:15)
at Socket.EventEmitter.emit (domain.js:448:20)
at endReadableNT (_stream_readable.js:1129:12)
at process._tickCallback (internal/process/next_tick.js:63:19)
code: 'ECONNRESET',
config: {
url: 'http://localhost:3000/api/option',
method: 'get',
headers: [Object],
baseURL: 'http://localhost:3000/',
transformRequest: [Array],
transformResponse: [Array],
timeout: 0,
adapter: [Function: httpAdapter],
xsrfCookieName: 'XSRF-TOKEN',
xsrfHeaderName: 'X-XSRF-TOKEN',
maxContentLength: -1,
validateStatus: [Function: validateStatus],
data: undefined
},
request: Writable {
_writableState: [WritableState],
writable: true,
domain: null,
_events: [Object],
_eventsCount: 2,
_maxListeners: undefined,
_options: [Object],
_redirectCount: 0,
_redirects: [],
_requestBodyLength: 0,
_requestBodyBuffers: [],
_onNativeResponse: [Function],
_currentRequest: [ClientRequest],
_currentUrl: 'http://localhost:3000/api/option'
},
response: undefined,
isAxiosError: true,
toJSON: [Function]
}
}
I would appreciate any help :)
I tried to use as many options as I thought was relevant in the proxy module, but ended up nowhere. I think you should create an issue on either #nuxtjs/proxy or on http-proxy-middleware github.
On my end the proxy route works without a problem with Vue's normal lifecycles, but will end up with a socket hang up when placed in asyncData or fetch - so I assume it's a SSR issue.
I don't have any problems with CORS, so I ended up creating module clones of the axios-module with custom prototypes. This setup unfortunately doesn't work alongside the axios-module as that also creates a socket hangup regardless of whether I have a proxy setup.
https://stackoverflow.com/a/43439886/1989083
I fixed my same issue by adding these lines into axios.js:
delete process.env['http_proxy'];
delete process.env['HTTP_PROXY'];
delete process.env['https_proxy'];
delete process.env['HTTPS_PROXY'];

Shared MongoDb collection between two meteor apps deployed in amazon AWS not working.

I have deployed a meteor app to port 80 of my AWS instance using MUP. I deployed a second meteor app to port 3000, but this time omitting mongo setup and specifying mongo url in the mup.js file. The setup works fine and the second app is deployed but none of my publications seems to work. I have tried the same setup with two test Apps previously and it worked.
MUP.JS of App 1
module.exports = {
servers: {
one: {
host: 'IP',
username: 'ubuntu',
pem: 'path to my pem file'
}
},
meteor: {
name: 'Dashboard',
path: 'Path to my project',
servers: {
one: {}
},
buildOptions: {
serverOnly: true,
},
docker: {
image: 'abernix/meteord:base',
},
env: {
PORT: 80,
ROOT_URL: 'base url/',
MONGO_URL: 'mongodb://mongodb:27017/dbname'
},
deployCheckWaitTime: 320,
enableUploadProgressBar: true
},
mongo: {
oplog: true,
port: 27017,
servers: {
one: {},
},
},
};
MUP.JS of App 2
module.exports = {
servers: {
one: {
host: 'IP',
username: 'ubuntu',
pem: 'path to my pem file'
}
},
meteor: {
name: 'DashBoard2',
path: 'Path to my project',
servers: {
one: {}
},
buildOptions: {
serverOnly: true,
},
docker: {
image: 'abernix/meteord:base',
},
env: {
PORT: 3000,
ROOT_URL: 'base url/',
MONGO_URL: 'mongodb://mongodb:27017/dbname'
},
deployCheckWaitTime: 320,
enableUploadProgressBar: true
},
};
Are you certain the connection to the database has been made? Typically the Meteor console will give an error if it can't connect to the MongoDB database. Also not sure if you have omitted your connection string, but it should be;
mongodb://user:password#server:port/database

Can't connect to mongodb from mocha test

Connecting from the REPL works fine:
> var mongoose=require('mongoose');
undefined
> mongoose.connect('mongodb://localhost/test', function(error) {
... console.log( 'connected\n%s\n', error );
... });
returns:
{ connections:
[ { base: [Circular],
collections: {},
models: {},
replica: false,
hosts: null,
host: 'localhost',
port: 27017,
user: undefined,
pass: undefined,
name: 'test',
options: [Object],
_readyState: 2,
_closeCalled: false,
_hasOpened: false,
_listening: false,
_events: {},
db: [Object] } ],
plugins: [],
models: {},
modelSchemas: {},
options: {} }
> connected # Yes!
undefined
But connecting from a Mocha test suite does not work:
var mongoose = require( 'mongoose' );
console.log( 'connecting...' );
mongoose.connect( 'mongodb://localhost/test', function( error ) {
if( error) console.error( 'Error while connecting:\n%\n', error );
console.log( 'connected' );
});
returns:
$ mocha
connecting...
0 passing (0 ms)
Does anyone know why this not working?
Do you have any tests in your suite? If not it seems like mocha exits before mongoose gets a chance to connect. One of the features listed on the mocha page is
auto-exit to prevent "hanging" with an active loop
which may have something to do with it. You could try connecting to mongoose in the before method of your test suite e.g.
describe('test suite', function() {
before(function(done) {
mongoose.connect('mongodb://localhost/test', function(error) {
if (error) console.error('Error while connecting:\n%\n', error);
console.log('connected');
done(error);
});
});
});