Error: connection timeout - expressjs mongodb mongoose - mongodb

I'm new to express/node and web programming in general. What is the best way to deal with this error when mongoose's mongodb connection times out, this is how I connect:
mongoose.connect(config.mongoUrl);
const db = mongoose.connection;
db.on('error', console.error.bind(console, 'error connecting with mongodb database:'));
db.once('open', function() {
console.log('connected to mongodb database');
});
This is the error when it times out while my server is running:
error connecting with mongodb database: Error: connection timeout
at Db. (C:\Users\Sean\OneDrive\webpages\000\lasttry\node_modules\mongoose\lib\drivers\node-mongodb-native\connection.js:169:17)
at emitTwo (events.js:106:13)
at Db.emit (events.js:191:7)
at Server.listener (C:\Users\Sean\OneDrive\webpages\000\lasttry\node_modules\mongodb\lib\db.js:1798:14)
at emitOne (events.js:96:13)
at Server.emit (events.js:188:7)
at Server. (C:\Users\Sean\OneDrive\webpages\000\lasttry\node_modules\mongodb\lib\server.js:274:14)
at emitOne (events.js:96:13)
at Server.emit (events.js:188:7)
at Pool. (C:\Users\Sean\OneDrive\webpages\000\lasttry\node_modules\mongodb-core\lib\topologies\server.js:335:12)
at emitOne (events.js:96:13)
at Pool.emit (events.js:188:7)
at Connection. (C:\Users\Sean\OneDrive\webpages\000\lasttry\node_modules\mongodb-core\lib\connection\pool.js:270:12)
at Connection.g (events.js:291:16)
at emitTwo (events.js:106:13)
at Connection.emit (events.js:191:7)

How about on disconnect just reconnect to mongo. See below:
mongoose.connect(config.mongoUrl);
var db = mongoose.connection;
db.on('error', console.error.bind(console, 'error connecting with mongodb database:'));
db.once('open', function() {
console.log('connected to mongodb database');
});
db.on('disconnected', function () {
//Reconnect on timeout
mongoose.connect(config.mongoUrl);
db = mongoose.connection;
});
You can also set a timeout value on the connection.
mongoose.connect(url, { server: { socketOptions: { connectTimeoutMS: 1000 }}}, function(err) { ... });
Also, make sure that mongo is still running on your machine. A connection timeout could mean mongo isn't running.
Reference: Another stack overflow question

Check mongod is running.
typing mongo in shell.
Add connectTimeoutMS=300000 paramter for you uri.
uri looks like mongodb://localhost/collectionName?connectTimeoutMS=300000

Related

GitLab pipeline - postgres connection termined unexpectedly

I am having a little trouble with postgres in docker .. I am running this pipeline in gitlab ... and everything starts fine.. I start a postgres:14-alpine docker image and run unit tests of the application ... and when it's about to start (create the test database) ...
I tried increasing the timeouts
pool: {
max: 50,
min: 5,
idle: 600000, // 10min
acquire: 600000,
createTimeoutMillis: 600000,
acquireTimeoutMillis: 600000,
idleTimeoutMillis: 600000,
reapIntervalMillis: 600000,
createRetryIntervalMillis: 600000
}
but it keeps ending up with this "Connection terminated unexpectedly"
Creating database db_unittests, owner will be postgres.
Executing (default): CREATE DATABASE db_unittests WITH OWNER = postgres;
/builds/project/node_modules/sequelize/lib/dialects/postgres/query.js:386
return new sequelizeErrors.DatabaseError(err);
^
DatabaseError [SequelizeDatabaseError]: Connection terminated unexpectedly
at Query.formatError (/builds/project/node_modules/sequelize/lib/dialects/postgres/query.js:386:16)
at Query.run (/builds/project/node_modules/sequelize/lib/dialects/postgres/query.js:87:18)
at processTicksAndRejections (node:internal/process/task_queues:96:5)
at async /builds/project/node_modules/sequelize/lib/sequelize.js:619:16
at async run (/builds/project/tests/scripts/database-recreate.js:50:3) {
parent: Error: Connection terminated unexpectedly
at Connection.<anonymous> (/builds/project/node_modules/pg/lib/client.js:132:73)
at Object.onceWrapper (node:events:627:28)
at Connection.emit (node:events:513:28)
at Socket.<anonymous> (/builds/project/node_modules/pg/lib/connection.js:107:12)
at Socket.emit (node:events:525:35)
at endReadableNT (node:internal/streams/readable:1358:12)
at processTicksAndRejections (node:internal/process/task_queues:83:21) {
sql: 'CREATE DATABASE db_unittests WITH OWNER = postgres;',
parameters: undefined
},
original: Error: Connection terminated unexpectedly
at Connection.<anonymous> (/builds/project/node_modules/pg/lib/client.js:132:73)
at Object.onceWrapper (node:events:627:28)
at Connection.emit (node:events:513:28)
at Socket.<anonymous> (/builds/project/node_modules/pg/lib/connection.js:107:12)
at Socket.emit (node:events:525:35)
at endReadableNT (node:internal/streams/readable:1358:12)
at processTicksAndRejections (node:internal/process/task_queues:83:21) {
sql: 'CREATE DATABASE db_unittests WITH OWNER = postgres;',
parameters: undefined
},
sql: 'CREATE DATABASE db_unittests WITH OWNER = postgres;',
parameters: undefined
}
Locally, it all works fine .. only in the pipeline - it acting up :disappointed:
Any idea why is that so? Thanks a lot

Heroku app fails to connect to mongodb atlas server (after migration from mlab)

I recently migrated from mlab to mongodb atlas due to its deprecation. I managed to successfully get a connection to the db and tested it with the mongoDB compass but when I add the environment variable to heroku it gives me the following error message:
MongoNetworkError: failed to connect to server [cluster-grwbxfbx-shard-00-02.e6jtl.mongodb.net:27017] on first connect [MongoNetworkError: connection 4 to cluster-grwbxfbx-shard-00-02.e6jtl.mongodb.net:27017 closed
2020-11-11T23:53:44.726144+00:00 app[web.1]: at TLSSocket.<anonymous> (/app/node_modules/mongodb/lib/core/connection/connection.js:372:9)
2020-11-11T23:53:44.726144+00:00 app[web.1]: at Object.onceWrapper (events.js:421:26)
2020-11-11T23:53:44.726145+00:00 app[web.1]: at TLSSocket.emit (events.js:314:20)
2020-11-11T23:53:44.726145+00:00 app[web.1]: at net.js:676:12
2020-11-11T23:53:44.726146+00:00 app[web.1]: at TCP.done (_tls_wrap.js:568:7)]
2020-11-11T23:53:44.726147+00:00 app[web.1]: at Pool.<anonymous> (/app/node_modules/mongodb/lib/core/topologies/server.js:438:11)
2020-11-11T23:53:44.726147+00:00 app[web.1]: at Pool.emit (events.js:314:20)
2020-11-11T23:53:44.726148+00:00 app[web.1]: at /app/node_modules/mongodb/lib/core/connection/pool.js:562:14
2020-11-11T23:53:44.726149+00:00 app[web.1]: at /app/node_modules/mongodb/lib/core/connection/pool.js:1009:9
2020-11-11T23:53:44.726149+00:00 app[web.1]: at callback (/app/node_modules/mongodb/lib/core/connection/connect.js:97:5)
2020-11-11T23:53:44.726150+00:00 app[web.1]: at /app/node_modules/mongodb/lib/core/connection/connect.js:124:7
2020-11-11T23:53:44.726150+00:00 app[web.1]: at _callback (/app/node_modules/mongodb/lib/core/connection/connect.js:349:5)
2020-11-11T23:53:44.726151+00:00 app[web.1]: at Connection.errorHandler (/app/node_modules/mongodb/lib/core/connection/connect.js:365:5)
2020-11-11T23:53:44.726151+00:00 app[web.1]: at Object.onceWrapper (events.js:421:26)
2020-11-11T23:53:44.726151+00:00 app[web.1]: at Connection.emit (events.js:314:20)
2020-11-11T23:53:44.726152+00:00 app[web.1]: at TLSSocket.<anonymous> (/app/node_modules/mongodb/lib/core/connection/connection.js:370:12)
2020-11-11T23:53:44.726152+00:00 app[web.1]: at Object.onceWrapper (events.js:421:26)
2020-11-11T23:53:44.726153+00:00 app[web.1]: at TLSSocket.emit (events.js:314:20)
2020-11-11T23:53:44.726153+00:00 app[web.1]: at net.js:676:12
2020-11-11T23:53:44.726153+00:00 app[web.1]: at TCP.done (_tls_wrap.js:568:7)
2020-11-11T23:53:44.812696+00:00 heroku[web.1]: Process exited with status 0
2020-11-11T23:53:44.850554+00:00 heroku[web.1]: State changed from starting to crashed
2020-11-11T23:53:44.854049+00:00 heroku[web.1]: State changed from crashed to starting
2020-11-11T23:53:47.149749+00:00 heroku[web.1]: Starting process with command `npm start`
2020-11-11T23:53:49.907225+00:00 app[web.1]:
It seems as if heroku is adding a port to the end of the MONGODB_URI. Does anyone know whats going on?
my config var in heroku is:
MONGODB_URI = mongodb+srv://username:password#cluster-grwbxfbx.e6jtl.mongodb.net/test?retryWrites=true&w=majority
with username and password being replaced by my admin username and password.
Also here is my code for connecting to the db
import mongoose from 'mongoose'
import options from '../config'
export const connect = (url = options.dbUrl, opts = {}) => {
return mongoose.connect(url, { ...opts, useNewUrlParser: true })
}
export const config = {
secrets: {
jwt: 'learneverything'
},
dbUrl: process.env.MONGODB_URI || 'mongodb://localhost:27017/api-design'
}
Let me know if you need me to post anything else

What is this Mongoose CursorNotFound Error?

I have mongoose throwing this error from time to time, it's not stopping the node application from running but I can't find any information about whats causing the error and I would like to fix it.
The link to the repo is here https://github.com/bkawk/divergence2
I have found I can stop the error by adding a limit to the records here
https://github.com/bkawk/divergence2/blob/master/src/db.js#L94
{ MongoError: cursor id 31871209567 not found
at /Users/bkawk/Documents/divergence2/node_modules/mongoose/node_modules/mongodb-core/lib/connection/pool.js:598:61
at authenticateStragglers (/Users/bkawk/Documents/divergence2/node_modules/mongoose/node_modules/mongodb-core/lib/connection/pool.js:516:16)
at Connection.messageHandler (/Users/bkawk/Documents/divergence2/node_modules/mongoose/node_modules/mongodb-core/lib/connection/pool.js:552:5)
at emitMessageHandler (/Users/bkawk/Documents/divergence2/node_modules/mongoose/node_modules/mongodb-core/lib/connection/connection.js:309:10)
at Socket.<anonymous> (/Users/bkawk/Documents/divergence2/node_modules/mongoose/node_modules/mongodb-core/lib/connection/connection.js:488:15)
at emitOne (events.js:116:13)
at Socket.emit (events.js:211:7)
at addChunk (_stream_readable.js:263:12)
at readableAddChunk (_stream_readable.js:250:11)
at Socket.Readable.push (_stream_readable.js:208:10)
at TCP.onread (net.js:607:20)
name: 'MongoError',
message: 'cursor id 31871209567 not found',
ok: 0,
errmsg: 'cursor id 31871209567 not found',
code: 43,
codeName: 'CursorNotFound' }

Google OAuth2 callback error

Very, very new to user authentication. Looking to allow users to register with Google.
Current status: I'm successfully making it to this step -
(hiding my email(s))
But, when I click an account, I'm getting this error (500) (using longjohn for longer stack traces):
Error
at /Users/johnsoct/Dropbox/Development/squashtomato/node_modules/passport-google-oauth20/lib/strategy.js:95:21
at passBackControl (/Users/johnsoct/Dropbox/Development/squashtomato/node_modules/oauth/lib/oauth2.js:132:9)
at IncomingMessage.<anonymous> (/Users/johnsoct/Dropbox/Development/squashtomato/node_modules/oauth/lib/oauth2.js:157:7)
at emitNone (events.js:91:20)
at IncomingMessage.emit (events.js:188:7)
at endReadableNT (_stream_readable.js:975:12)
at _combinedTickCallback (internal/process/next_tick.js:80:11)
at process._tickCallback (internal/process/next_tick.js:104:9)
---------------------------------------------
at IncomingMessage.Readable.on (_stream_readable.js:689:35)
at ClientRequest.<anonymous> (/Users/johnsoct/Dropbox/Development/squashtomato/node_modules/oauth/lib/oauth2.js:156:14)
at emitOne (events.js:96:13)
at ClientRequest.emit (events.js:191:7)
at HTTPParser.parserOnIncomingClient (_http_client.js:522:21)
at HTTPParser.parserOnHeadersComplete (_http_common.js:99:23)
at TLSSocket.socketOnData (_http_client.js:411:20)
at emitOne (events.js:96:13)
at TLSSocket.emit (events.js:191:7)
at readableAddChunk (_stream_readable.js:178:18)
at TLSSocket.Readable.push (_stream_readable.js:136:10)
at TLSWrap.onread (net.js:560:20)
---------------------------------------------
at exports.OAuth2._executeRequest (/Users/johnsoct/Dropbox/Development/squashtomato/node_modules/oauth/lib/oauth2.js:147:11)
at exports.OAuth2._request (/Users/johnsoct/Dropbox/Development/squashtomato/node_modules/oauth/lib/oauth2.js:120:8)
at exports.OAuth2.get (/Users/johnsoct/Dropbox/Development/squashtomato/node_modules/oauth/lib/oauth2.js:227:8)
at Strategy.userProfile (/Users/johnsoct/Dropbox/Development/squashtomato/node_modules/passport-google-oauth20/lib/strategy.js:84:16)
at loadIt (/Users/johnsoct/Dropbox/Development/squashtomato/node_modules/passport-oauth2/lib/strategy.js:345:17)
at Strategy.OAuth2Strategy._loadUserProfile (/Users/johnsoct/Dropbox/Development/squashtomato/node_modules/passport-oauth2/lib/strategy.js:360:25)
at /Users/johnsoct/Dropbox/Development/squashtomato/node_modules/passport-oauth2/lib/strategy.js:168:16
at /Users/johnsoct/Dropbox/Development/squashtomato/node_modules/oauth/lib/oauth2.js:209:7
at passBackControl (/Users/johnsoct/Dropbox/Development/squashtomato/node_modules/oauth/lib/oauth2.js:134:9)
at IncomingMessage.<anonymous> (/Users/johnsoct/Dropbox/Development/squashtomato/node_modules/oauth/lib/oauth2.js:157:7)
at emitNone (events.js:91:20)
at IncomingMessage.emit (events.js:188:7)
at endReadableNT (_stream_readable.js:975:12)
at _combinedTickCallback (internal/process/next_tick.js:80:11)
at process._tickCallback (internal/process/next_tick.js:104:9)
---------------------------------------------
at IncomingMessage.Readable.on (_stream_readable.js:689:35)
at ClientRequest.<anonymous> (/Users/johnsoct/Dropbox/Development/squashtomato/node_modules/oauth/lib/oauth2.js:156:14)
at emitOne (events.js:96:13)
at ClientRequest.emit (events.js:191:7)
at HTTPParser.parserOnIncomingClient (_http_client.js:522:21)
at HTTPParser.parserOnHeadersComplete (_http_common.js:99:23)
at TLSSocket.socketOnData (_http_client.js:411:20)
at emitOne (events.js:96:13)
at TLSSocket.emit (events.js:191:7)
at readableAddChunk (_stream_readable.js:178:18)
at TLSSocket.Readable.push (_stream_readable.js:136:10)
at TLSWrap.onread (net.js:560:20)
---------------------------------------------
at exports.OAuth2._executeRequest (/Users/johnsoct/Dropbox/Development/squashtomato/node_modules/oauth/lib/oauth2.js:147:11)
at exports.OAuth2._request (/Users/johnsoct/Dropbox/Development/squashtomato/node_modules/oauth/lib/oauth2.js:120:8)
at exports.OAuth2.getOAuthAccessToken (/Users/johnsoct/Dropbox/Development/squashtomato/node_modules/oauth/lib/oauth2.js:190:8)
at loaded (/Users/johnsoct/Dropbox/Development/squashtomato/node_modules/passport-oauth2/lib/strategy.js:164:20)
at NullStore.verify (/Users/johnsoct/Dropbox/Development/squashtomato/node_modules/passport-oauth2/lib/state/null.js:9:3)
at Strategy.OAuth2Strategy.authenticate (/Users/johnsoct/Dropbox/Development/squashtomato/node_modules/passport-oauth2/lib/strategy.js:210:26)
at attempt (/Users/johnsoct/Dropbox/Development/squashtomato/node_modules/passport/lib/middleware/authenticate.js:348:16)
at authenticate (/Users/johnsoct/Dropbox/Development/squashtomato/node_modules/passport/lib/middleware/authenticate.js:349:7)
at Layer.handle [as handle_request] (/Users/johnsoct/Dropbox/Development/squashtomato/node_modules/express/lib/router/layer.js:95:5)
at next (/Users/johnsoct/Dropbox/Development/squashtomato/node_modules/express/lib/router/route.js:137:13)
at Route.dispatch (/Users/johnsoct/Dropbox/Development/squashtomato/node_modules/express/lib/router/route.js:112:3)
at Layer.handle [as handle_request] (/Users/johnsoct/Dropbox/Development/squashtomato/node_modules/express/lib/router/layer.js:95:5)
at /Users/johnsoct/Dropbox/Development/squashtomato/node_modules/express/lib/router/index.js:281:22
at Function.process_params (/Users/johnsoct/Dropbox/Development/squashtomato/node_modules/express/lib/router/index.js:335:12)
at next (/Users/johnsoct/Dropbox/Development/squashtomato/node_modules/express/lib/router/index.js:275:10)
at Function.handle (/Users/johnsoct/Dropbox/Development/squashtomato/node_modules/express/lib/router/index.js:174:3)
at router (/Users/johnsoct/Dropbox/Development/squashtomato/node_modules/express/lib/router/index.js:47:12)
at Layer.handle [as handle_request] (/Users/johnsoct/Dropbox/Development/squashtomato/node_modules/express/lib/router/layer.js:95:5)
at trim_prefix (/Users/johnsoct/Dropbox/Development/squashtomato/node_modules/express/lib/router/index.js:317:13)
at /Users/johnsoct/Dropbox/Development/squashtomato/node_modules/express/lib/router/index.js:284:7
at Function.process_params (/Users/johnsoct/Dropbox/Development/squashtomato/node_modules/express/lib/router/index.js:335:12)
---------------------------------------------
at handleOperationCallback (/Users/johnsoct/Dropbox/Development/squashtomato/node_modules/mongoose/node_modules/mongodb-core/lib/connection/pool.js:454:24)
at /Users/johnsoct/Dropbox/Development/squashtomato/node_modules/mongoose/node_modules/mongodb-core/lib/connection/pool.js:490:9
at authenticateStragglers (/Users/johnsoct/Dropbox/Development/squashtomato/node_modules/mongoose/node_modules/mongodb-core/lib/connection/pool.js:429:16)
at Connection.messageHandler (/Users/johnsoct/Dropbox/Development/squashtomato/node_modules/mongoose/node_modules/mongodb-core/lib/connection/pool.js:463:5)
at Socket.<anonymous> (/Users/johnsoct/Dropbox/Development/squashtomato/node_modules/mongoose/node_modules/mongodb-core/lib/connection/connection.js:319:22)
at emitOne (events.js:96:13)
at Socket.emit (events.js:191:7)
at readableAddChunk (_stream_readable.js:178:18)
at Socket.Readable.push (_stream_readable.js:136:10)
at TCP.onread (net.js:560:20)
My code surrounding this functionality is:
// routes.js
router.get('/auth/google', authController.google);
router.get('/oauth2callback', authController.googleCallback
);
// passport.js
const GoogleStrategy = require('passport-google-oauth').OAuth2Strategy;
passport.serializeUser(User.serializeUser());
passport.deserializeUser(User.deserializeUser());
passport.use(new GoogleStrategy({
clientID: process.env.GOOGLE_CONSUMER_KEY,
clientSecret: process.env.GOOGLE_CONSUMER_SECRET,
callbackURL: "http://localhost:21015/auth/google/callback"
},
function(accessToken, refreshToken, profile, done) {
const user = new User();
user.google.id = profile.id;
user.google.token = accessToken;
user.google.name = profile.displayName;
user.google.email = profile.emails[0].value;
user.save(function(err) {
if (err) throw err;
return done(null, user);
});
}
));
// authController.js
const passport = require('passport');
exports.google = passport.authenticate('google', {
scope: 'https://www.google.com/m8/feeds'
});
exports.googleCallback = passport.authenticate('google', {
failureRedirect: '/login', // if fail, where to go
failureFlash: 'Failed Login!', // if fail, what to flash
successRedirect: '/', // if success, where to go
successFlash: 'You are now logged in!' // if success, what to flash
});
Apparently you can not use an IP address as and end-point, so try to change your callback-url to : http://localhost:21015/oauth2callback
Make sure you have enabled Google+ API in https://console.cloud.google.com.
To use google Auth you have to enable the API in google console. A very common mistake is when you go to Google Developer Console to enable an API for your project, first time for a project it asks you to create Credentials. The problem is after you create credentials the google+ API (or any other APIs) won't be enabled automatically and you should enable it from your project page in google developer console.
STEPS:
Go to Google Console
Select your project from the top nav (if you didn't yet)
Click on Enable APIS and Services
In the search box search for Google Plus
Select the first result , Google+ API
Click Enable
If you don't see the Enable button and see the 'Create Credentials' button,it means you didn't create credentials yet and follow the instructions on the page to create one. Don't forget to enable API after creating credentials.
For more information you can read this instruction from google Enable and disable APIs
Besides what mentioned above, you don't need to use an absolute URL for your callback and simply you can use a relative one like: /auth/google/callback
passport.use(new GoogleStrategy({
clientID: process.env.GOOGLE_CONSUMER_KEY,
clientSecret: process.env.GOOGLE_CONSUMER_SECRET,
callbackURL: "/auth/google/callback"
},
function(accessToken, refreshToken, profile, done) {
const user = new User();
user.google.id = profile.id;
user.google.token = accessToken;
user.google.name = profile.displayName;
user.google.email = profile.emails[0].value;
user.save(function(err) {
if (err) throw err;
return done(null, user);
});
}
));

Heroku Deployment Issues with Postgres and Sequelize

I am trying to deploy my app to Heroku. It works perfectly fine when run locally. From the moment I deployed it (deploying through github integration) I received the generic Application Error screen. Below are my heroku logs. These actually run three times but there was no point in me posting the same thing three times. They always end with:
2017-05-02T14:59:26.033702+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=calm-crag-40902.herokuapp.com request_id=6b64883e-9697-4d58-84d9-2f173d5b4cb1 fwd="70.
54.76.222" dyno= connect= service= status=503 bytes= protocol=https
2017-05-02T14:59:27.425435+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/favicon.ico" host=calm-crag-40902.herokuapp.com request_id=d3719d8f-4670-4621-a044-a511ee6884
10 fwd="70.54.76.222" dyno= connect= service= status=503 bytes= protocol=https
This will print 2 to 4 times after each consecutive error screen. The first error is regarding the .env files not running and the second is trying to connect to sequelize. My primary focus is sorting out the .env because if that is sorted out, at least the app will show my app will be visible.
.env error:
{ Error: ENOENT: no such file or directory, open '.env'
2017-05-02T16:09:39.622865+00:00 app[web.1]: at Error (native)
2017-05-02T16:09:39.622866+00:00 app[web.1]: at Object.fs.openSync (fs.js:641:18)
2017-05-02T16:09:39.622867+00:00 app[web.1]: at Object.fs.readFileSync (fs.js:509:33)
2017-05-02T16:09:39.622867+00:00 app[web.1]: at Object.config (/app/node_modules/dotenv/lib/main.js:30:37)
2017-05-02T16:09:39.622868+00:00 app[web.1]: at Object.<anonymous> (/app/server.js:3:19)
2017-05-02T16:09:39.622869+00:00 app[web.1]: at Module._compile (module.js:570:32)
2017-05-02T16:09:39.622869+00:00 app[web.1]: at Object.Module._extensions..js (module.js:579:10)
2017-05-02T16:09:39.622870+00:00 app[web.1]: at Module.load (module.js:487:32)
2017-05-02T16:09:39.622871+00:00 app[web.1]: at tryModuleLoad (module.js:446:12)
2017-05-02T16:09:39.622871+00:00 app[web.1]: at Function.Module._load (module.js:438:3) errno: -2, code: 'ENOENT', syscall: 'open', path: '.env' }
2017-05-02T16:09:40.242885+00:00 app[web.1]: Unhandled rejection
Sequelize error:
SequelizeConnectionRefusedError: connect ECONNREFUSED 127.0.0.1:5432
2017-05-02T16:09:40.242902+00:00 app[web.1]: at /app/node_modules/sequelize/lib/dialects/postgres/connection-manager.js:98:20
2017-05-02T16:09:40.242903+00:00 app[web.1]: at Connection.<anonymous> (/app/node_modules/pg/lib/client.js:186:5)
2017-05-02T16:09:40.242904+00:00 app[web.1]: at emitOne (events.js:96:13)
2017-05-02T16:09:40.242905+00:00 app[web.1]: at Connection.emit (events.js:188:7)
2017-05-02T16:09:40.242905+00:00 app[web.1]: at Socket.<anonymous> (/app/node_modules/pg/lib/connection.js:86:10)
2017-05-02T16:09:40.242906+00:00 app[web.1]: at emitOne (events.js:96:13)
2017-05-02T16:09:40.242907+00:00 app[web.1]: at emitErrorNT (net.js:1281:8)
2017-05-02T16:09:40.242907+00:00 app[web.1]: at Socket.emit (events.js:188:7)
2017-05-02T16:09:40.242909+00:00 app[web.1]: at process._tickCallback (internal/process/next_tick.js:104:9)
2017-05-02T16:09:40.242908+00:00 app[web.1]: at _combinedTickCallback (internal/process/next_tick.js:80:11)
2017-05-02T16:09:40.360035+00:00 heroku[web.1]: Process exited with status 0
2017-05-02T16:09:40.373996+00:00 heroku[web.1]: State changed from starting to crashed
This is my index.js:
'use strict';
const fs = require('fs');
const path = require('path');
const Sequelize = require('sequelize');
const basename = path.basename(module.filename);
const env = process.env.NODE_ENV || 'development';
const config = require(__dirname + '/../config/config.json')[env];
const db = {};
if (config.use_env_variable) {
const sequelize = new Sequelize(process.env[config.use_env_variable]);
} else {
const sequelize = new Sequelize(config.database, config.username, config.password, config);
}
fs
.readdirSync(__dirname)
.filter((file) => {
return (file.indexOf('.') !== 0) && (file !== basename) && (file.slice(-3) === '.js');
})
.forEach((file) => {
const model = sequelize['import'](path.join(__dirname, file));
db[model.name] = model;
});
Object.keys(db).forEach((modelName) => {
if (db[modelName].associate) {
db[modelName].associate(db);
}
});
db.sequelize = sequelize;
db.Sequelize = Sequelize;
module.exports = db;
config.json:
{
"development": {
"username": "",
"password": "",
"database": "late_file",
"host": "127.0.0.1",
"dialect": "postgres"
},
"test": {
"username": "",
"password": "",
"database": "database_test",
"host": "127.0.0.1",
"dialect": "postgres"
},
"production": {
"use_env_variable": "DATABASE_URL",
"dialect": "postgres"
}
}
.env, modified to exclude specific names of things
DB_HOST=localhost
DB_USER=
DB_PASS=
DB_NAME=
DB_SSL=true if heroku
DB_PORT=5432
DATABASE_URL=postgres://appropriate/url
applicable part of server.js
const pg = require('pg');
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));
});
});
Any help would be greatly appreciated!
Thanks in advance for anyone who offers any support!
Brandon,
I am running an app on Heroku using JAWS_DB and MySQL, but otherwise identical config.json and index.js. In my case on Heroku, the "if (config.use_env_variable) {const sequelize = new Sequelize(process.env[config.use_env_variable])" statement connects to the database without error. The logs appear to point to the "pg.connect" failing in server.js. It's not clear to me (without seeing the rest of your code) why you need to connect to the database in index.js, and then connect again in server.js. If you can remove the connection from pg.connect and try to run with just the connection from index.js it may stop this error.