Vercel Serverless sequelize connect ECONNREFUSED - node.js

I'm using Vercl's serverless functions and Sequelize for postgres, i have tested the connection on my local machine using vercel dev command and everything is working fine.
but when i deploy it, the connection to postgres RDS is very unpredictable, it sometimes works but if i make two requests 1 minute apart from each other i get
ConnectionRefusedError [SequelizeConnectionRefusedError]: connect ECONNREFUSED 127.0.0.1:5432
at Client._connectionCallback (/var/task/node_modules/sequelize/lib/dialects/postgres/connection-manager.js:172:24)
at Client._handleErrorWhileConnecting (/var/task/node_modules/pg/lib/client.js:305:19)
at Client._handleErrorEvent (/var/task/node_modules/pg/lib/client.js:315:19)
at Connection.emit (events.js:314:20)
at Connection.EventEmitter.emit (domain.js:483:12)
at Socket.reportStreamError (/var/task/node_modules/pg/lib/connection.js:53:12)
at Socket.emit (events.js:314:20)
at Socket.EventEmitter.emit (domain.js:483:12)
at emitErrorNT (internal/streams/destroy.js:92:8)
at emitErrorAndCloseNT (internal/streams/destroy.js:60:3) {
parent: Error: connect ECONNREFUSED 127.0.0.1:5432
at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1144:16) {
errno: 'ECONNREFUSED',
code: 'ECONNREFUSED',
syscall: 'connect',
address: '127.0.0.1',
port: 5432
},
original: Error: connect ECONNREFUSED 127.0.0.1:5432
at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1144:16) {
errno: 'ECONNREFUSED',
code: 'ECONNREFUSED',
syscall: 'connect',
address: '127.0.0.1',
port: 5432
}
}
i suspected this might be due to serverless nature of Vercel functions, tried to fiddle with pool connections, even tried closing and opening connections after every query but it doesn't seem to be working.
this is my connection
const pg = require('pg');
const { Sequelize } = require('sequelize');
new Sequelize(POSTGRES_DB, POSTGRES_USER_WEB, POSTGRES_USER_WEB_PASSWORD, {
host: POSTGRES_HOST, //AWS RDS HOST
dialectModule: pg,
dialect: 'postgres',
pool: {
max: 5,
min: 0,
idle: 1000,
handleDisconnects: true
}
});
this is my vercel.json
{
"version": 2,
"builds": [{ "src": "index.js", "use": "#vercel/node" }],
"rewrites": [
{ "source": "/(.*)", "destination": "index.js" },
{ "source": "/webhook", "destination": "index.js" },
{ "source": "/v1", "destination": "index.js" }
]
}
this is the error i get, i still suspect this has to do with pools but i don't know how to configure it.
[SequelizeConnectionRefusedError]: connect ECONNREFUSED 127.0.0.1:5432
at Client._connectionCallback (/var/task/node_modules/sequelize/lib/dialects/postgres/connection-manager.js:172:24)

Related

Running into a problem starting up mongoDB

I downloaded MongoDB with Compass and the shell as accessories and started learning from W3Schools Node.js MongoDB section.
Step 1: type into command prompt>npm install mongodb
success
step 2: create a MongoClient object file with this code and then save
var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://localhost:27017/mydb";
MongoClient.connect(url, function(err, db) {
if (err) throw err;
console.log("Database created!");
db.close();
});
Step 3: Once the code above is saved run the file by calling it on the command prompt
C:\Users\MyName>node fileName.js
and this is the response I'm getting
C:\Users\*****\MongoDB Tutorials>node demo_create_mongo_db.js
C:\Users\*****\node_modules\mongodb\lib\utils.js:418
throw error;
^
MongoServerSelectionError: connect ECONNREFUSED ::1:27017
at Timeout._onTimeout (C:\Users\*****\node_modules\mongodb\lib\sdam\topology.js:293:38)
at listOnTimeout (node:internal/timers:557:17)
at processTimers (node:internal/timers:500:7) {
reason: TopologyDescription {
type: 'Unknown',
servers: Map(1) {
'localhost:27017' => ServerDescription {
_hostAddress: HostAddress { isIPv6: false, host: 'localhost', port: 27017 },
address: 'localhost:27017',
type: 'Unknown',
hosts: [],
passives: [],
arbiters: [],
tags: {},
minWireVersion: 0,
maxWireVersion: 0,
roundTripTime: -1,
lastUpdateTime: 11442648,
lastWriteDate: 0,
error: MongoNetworkError: connect ECONNREFUSED ::1:27017
at connectionFailureError (C:\Users\*****\node_modules\mongodb\lib\cmap\connect.js:379:20)
at Socket.<anonymous> (C:\Users\*****\node_modules\mongodb\lib\cmap\connect.js:302:22)
at Object.onceWrapper (node:events:510:26)
at Socket.emit (node:events:390:28)
at emitErrorNT (node:internal/streams/destroy:164:8)
at emitErrorCloseNT (node:internal/streams/destroy:129:3)
at processTicksAndRejections (node:internal/process/task_queues:83:21) {
[Symbol(errorLabels)]: Set(0) {}
}
}
},
stale: false,
compatible: true,
heartbeatFrequencyMS: 10000,
localThresholdMS: 15,
logicalSessionTimeoutMinutes: undefined
},
code: undefined,
[Symbol(errorLabels)]: Set(0) {}
}
Node.js v17.2.0
What do I do about this?

Mongo server selection error. I keep getting an error in my terminal with respect to mongo error

const MongoClient = mongodb.MongoClient;
let database;
async function connectToDatabase() {
const client = await MongoClient.connect('mongodb:// 127.0.0.1.27017');
database = client.db('file-demo');
}
function getDb() {
if (!database) {
throw { message: 'Database not connected!' };
}
return database;
}
module.exports = {
connectToDatabase: connectToDatabase,
getDb: getDb,
};
Immediately i run npm start i get this error.
C:\Users\user\Documents\programming\100 Days Of Code (1)\Course Files\100-days-of-web-development-27-adding-file-upload\code\00-starting-project\node_modules\mongodb\lib\sdam\topology.js:305
const timeoutError = new error_1.MongoServerSelectionError(Server selection timed out after ${serverSelectionTimeoutMS} ms, this.description);
^
MongoServerSelectionError: getaddrinfo ENOTFOUND 127.0.0.1.27017
at Timeout._onTimeout (C:\Users\user\Documents\programming\100 Days Of Code (1)\Course Files\100-days-of-web-development-27-adding-file-upload\code\00-starting-project\node_modules\mongodb\lib\sdam\topology.js:305:38)
at listOnTimeout (node:internal/timers:559:17)
at processTimers (node:internal/timers:502:7) {
reason: TopologyDescription {
type: 'Unknown',
servers: Map(1) {
' 127.0.0.1.27017:27017' => ServerDescription {
_hostAddress: HostAddress {
isIPv6: false,
host: ' 127.0.0.1.27017',
port: 27017
},
address: ' 127.0.0.1.27017:27017',
type: 'Unknown',
hosts: [],
passives: [],
arbiters: [],
tags: {},
minWireVersion: 0,
maxWireVersion: 0,
roundTripTime: -1,
lastUpdateTime: 58035949,
lastWriteDate: 0,
error: MongoNetworkError: getaddrinfo ENOTFOUND 127.0.0.1.27017
at connectionFailureError (C:\Users\user\Documents\programming\100 Days Of Code (1)\Course Files\100-days-of-web-development-27-adding-file-upload\code\00-starting-project\node_modules\mongodb\lib\cmap\connect.js:382:20)
at Socket. (C:\Users\user\Documents\programming\100 Days Of Code (1)\Course Files\100-days-of-web-development-27-adding-file-upload\code\00-starting-project\node_modules\mongodb\lib\cmap\connect.js:302:22)
at Object.onceWrapper (node:events:642:26)
at Socket.emit (node:events:527:28)
at emitErrorNT (node:internal/streams/destroy:164:8)
at emitErrorCloseNT (node:internal/streams/destroy:129:3)
at processTicksAndRejections (node:internal/process/task_queues:83:21) {
[Symbol(errorLabels)]: Set(0) {}
}
}
code: undefined,
[Symbol(errorLabels)]: Set(0) {}
}
i also made sure my mongodb server is running in the background

My npm keeps crashing. What am i doing wrong?

The code:
const mongodb = require('mongodb');
const MongoClient = mongodb.MongoClient;
let dataBase;
async function connect() {
const client = await MongoClient.connect('mongodb://localhost:27017');
dataBase = client.db('blog');
};
function getDb() {
if (!dataBase) {
throw { message: "Database connection not established" };
}
return dataBase;
};
module.exports = {
connectToDatabase: connect,
getDb: getDb
};
I keep getting this message:
const timeoutError = new error_1.MongoServerSelectionError(`Server selection timed out after ${serverSelectionTimeoutMS} ms`, this.description);
...
MongoServerSelectionError: connect ECONNREFUSED ::1:27017
at Timeout._onTimeout (C:\Users\user\Documents\programming\100 Days Of Code (1)\Course Files\100-days-of-web-development-26-nodejs-mongodb\code\00-starting-project\node_modules\mongodb\lib\sdam\topology.js:305:38)
at listOnTimeout (node:internal/timers:559:17)
at processTimers (node:internal/timers:502:7) {
reason: TopologyDescription {
type: 'Unknown',
servers: Map(1) {
'localhost:27017' => ServerDescription {
_hostAddress: HostAddress { isIPv6: false, host: 'localhost', port: 27017 },
address: 'localhost:27017',
type: 'Unknown',
hosts: [],
passives: [],
arbiters: [],
tags: {},
minWireVersion: 0,
maxWireVersion: 0,
roundTripTime: -1,
lastUpdateTime: 85766126,
lastWriteDate: 0,
error: MongoNetworkError: connect ECONNREFUSED ::1:27017
at connectionFailureError (C:\Users\user\Documents\programming\100 Days Of Code (1)\Course Files\100-days-of-web-development-26-nodejs-mongodb\code\00-starting-project\node_modules\mongodb\lib\cmap\connect.js:382:20)
at Socket.<anonymous> (C:\Users\user\Documents\programming\100 Days Of Code (1)\Course Files\100-days-of-web-development-26-nodejs-mongodb\code\00-starting-project\node_modules\mongodb\lib\cmap\connect.js:302:22)
at Object.onceWrapper (node:events:642:26)
at Socket.emit (node:events:527:28)
at emitErrorNT (node:internal/streams/destroy:164:8)
at emitErrorCloseNT (node:internal/streams/destroy:129:3)
at processTicksAndRejections (node:internal/process/task_queues:83:21) {
[Symbol(errorLabels)]: Set(0) {}
}
}
},
stale: false,
compatible: true,
code: undefined,
[Symbol(errorLabels)]: Set(0) {}
}
try to change the mongodb://localhost:27017 to mongodb://127.0.0.1:27017 sometimes the localhost is not recognized.
I hope it was helpful

serverSelectionError when connect to localhost in mongoose?

Hi I tried every thing like mongoose.connect('mongodb://localhost/blog') but I am not able to connect mongoose to node here is my code....
const express = require('express')
const mongoose = require('mongoose')
const articleRouter = require('./routes/articles')
const app = express()
mongoose.connect('mongodb://localhost:27017/blog')
app.set('view engine','ejs')
Here is the error:
/home/vishwajeet/webdeve/MARKDOWN-BLOG/node_modules/mongoose/lib/connection.js:807
const serverSelectionError = new ServerSelectionError();
^
MongooseServerSelectionError: connect ECONNREFUSED 127.0.0.1:27017
at NativeConnection.Connection.openUri (/home/vishwajeet/webdeve/MARKDOWN-BLOG/node_modules/mongoose/lib/connection.js:807:32)
at /home/vishwajeet/webdeve/MARKDOWN-BLOG/node_modules/mongoose/lib/index.js:342:10
at /home/vishwajeet/webdeve/MARKDOWN-BLOG/node_modules/mongoose/lib/helpers/promiseOrCallback.js:32:5
at new Promise (<anonymous>)
at promiseOrCallback (/home/vishwajeet/webdeve/MARKDOWN-BLOG/node_modules/mongoose/lib/helpers/promiseOrCallback.js:31:10)
at Mongoose._promiseOrCallback (/home/vishwajeet/webdeve/MARKDOWN-BLOG/node_modules/mongoose/lib/index.js:1181:10)
at Mongoose.connect (/home/vishwajeet/webdeve/MARKDOWN-BLOG/node_modules/mongoose/lib/index.js:341:20)
at Object.<anonymous> (/home/vishwajeet/webdeve/MARKDOWN-BLOG/server.js:8:10)
at Module._compile (node:internal/modules/cjs/loader:1103:14)
at Object.Module._extensions..js (node:internal/modules/cjs/loader:1157:10) {
reason: TopologyDescription {
type: 'Unknown',
servers: Map(1) {
'localhost:27017' => ServerDescription {
_hostAddress: HostAddress { isIPv6: false, host: 'localhost', port: 27017 },
address: 'localhost:27017',
type: 'Unknown',
hosts: [],
passives: [],
arbiters: [],
tags: {},
minWireVersion: 0,
maxWireVersion: 0,
roundTripTime: -1,
lastUpdateTime: 774709,
lastWriteDate: 0,
error: MongoNetworkError: connect ECONNREFUSED 127.0.0.1:27017
at connectionFailureError (/home/vishwajeet/webdeve/MARKDOWN-BLOG/node_modules/mongodb/lib/cmap/connect.js:375:20)
at Socket.<anonymous> (/home/vishwajeet/webdeve/MARKDOWN-BLOG/node_modules/mongodb/lib/cmap/connect.js:295:22)
at Object.onceWrapper (node:events:646:26)
at Socket.emit (node:events:526:28)
at emitErrorNT (node:internal/streams/destroy:157:8)
at emitErrorCloseNT (node:internal/streams/destroy:122:3)
at processTicksAndRejections (node:internal/process/task_queues:83:21) {
[Symbol(errorLabels)]: Set(0) {}
}
}
},
stale: false,
compatible: true,
heartbeatFrequencyMS: 10000,
localThresholdMS: 15,
logicalSessionTimeoutMinutes: undefined
},
code: undefined
}
Hey I think your problem is that you don't have mongodb installed on your computer.
Once you download it you can change
mongoose.connect('mongodb://localhost:27017/blog')
to
mongoose.connect('mongodb://127.0.0.1/blog')
if the problem is still there
Youtube video for mongodb install

facing error while connecting mongodb with mongoose

Hi I am in arch based garuda linux and I am facing MongooseServerSelectionError: connect ECONNREFUSED ::1:27017 error while connecting my node app to mongodb.
The error is
MongooseServerSelectionError: connect ECONNREFUSED ::1:27017
at NativeConnection.Connection.openUri (/home/linux/Desktop/mongo tutorial/node_modules/mongoose/lib/connection.js:797:32)
at /home/linux/Desktop/mongo tutorial/node_modules/mongoose/lib/index.js:341:10
at /home/linux/Desktop/mongo tutorial/node_modules/mongoose/lib/helpers/promiseOrCallback.js:32:5
at new Promise (<anonymous>)
at promiseOrCallback (/home/linux/Desktop/mongo tutorial/node_modules/mongoose/lib/helpers/promiseOrCallback.js:31:10)
at Mongoose._promiseOrCallback (/home/linux/Desktop/mongo tutorial/node_modules/mongoose/lib/index.js:1167:10)
at Mongoose.connect (/home/linux/Desktop/mongo tutorial/node_modules/mongoose/lib/index.js:340:20)
at Object.<anonymous> (/home/linux/Desktop/mongo tutorial/index.js:2:10)
at Module._compile (node:internal/modules/cjs/loader:1097:14)
at Object.Module._extensions..js (node:internal/modules/cjs/loader:1149:10) { reason: TopologyDescription {
type: 'Unknown',
servers: Map(1) {
'localhost:27017' => ServerDescription {
_hostAddress: HostAddress { isIPv6: false, host: 'localhost', port: 27017 },
address: 'localhost:27017',
type: 'Unknown',
hosts: [],
passives: [],
arbiters: [],
tags: {},
minWireVersion: 0,
maxWireVersion: 0,
roundTripTime: -1,
lastUpdateTime: 19125836,
lastWriteDate: 0,
error: MongoNetworkError: connect ECONNREFUSED ::1:27017
at connectionFailureError (/home/linux/Desktop/mongo tutorial/node_modules/mongodb/lib/cmap/connect.js:293:20)
at Socket.<anonymous> (/home/linux/Desktop/mongo tutorial/node_modules/mongodb/lib/cmap/connect.js:267:22)
at Object.onceWrapper (node:events:510:26)
at Socket.emit (node:events:390:28)
at emitErrorNT (node:internal/streams/destroy:164:8)
at emitErrorCloseNT (node:internal/streams/destroy:129:3)
at processTicksAndRejections (node:internal/process/task_queues:83:21)
}
},
stale: false,
compatible: true,
heartbeatFrequencyMS: 10000,
localThresholdMS: 15,
logicalSessionTimeoutMinutes: undefined } }
Node.js v17.3.0
My mongodb compass screenschot
This is working on win 10.
mongoose.connect("mongodb://0.0.0.0/test-db");
The problem was not with the code it was the version.
Instead of using
mongoose.connect("mongodb://localhost/test")
I used
mongoose.connect("mongodb://127.0.0.1/test")
it worked.
reference: https://www.mongodb.com/community/forums/t/mongooseserverselectionerror-connect-econnrefused-127-0-0-1-27017/123421

Resources