Can't connect Node.js to remote database MariaDB - node.js

I try to connect to my MariaDB database using Node.js based on this tutorial:
const mariadb = require('mariadb');
const pool = mariadb.createPool({
host: 'myhost.com',
user:'root',
password: 'password',
database: 'db_p',
connectionLimit: 2
});
async function asyncFunction() {
let conn;
try {
console.log('establishing connection')
conn = await pool.getConnection();
console.log('established')
const rows = await conn.query("SHOW TABLES");
console.log(rows);
} catch (err) {
console.log(err)
throw err;
} finally {
if (conn) return conn.end();
}
}
but all I get is this error:
establishing connection
{ Error: retrieve connection from pool timeout
at Object.module.exports.createError (/Users/jan/Developer/microservice/node_modules/mariadb/lib/misc/errors.js:55:10)
at rejectTimeout (/Users/jan/Developer/microservice/node_modules/mariadb/lib/pool.js:267:16)
at Timeout.rejectAndResetTimeout [as _onTimeout] (/Users/jan/Developer/microservice/node_modules/mariadb/lib/pool.js:287:5)
at ontimeout (timers.js:486:15)
at tryOnTimeout (timers.js:317:5)
at Timer.listOnTimeout (timers.js:277:5)
fatal: false,
errno: 45028,
sqlState: 'HY000',
code: 'ER_GET_CONNECTION_TIMEOUT' }
(node:76515) UnhandledPromiseRejectionWarning: Error: retrieve connection from pool timeout
at Object.module.exports.createError (/Users/jan/Developer/microservice/node_modules/mariadb/lib/misc/errors.js:55:10)
at rejectTimeout (/Users/jan/Developer/microservice/node_modules/mariadb/lib/pool.js:267:16)
at Timeout.rejectAndResetTimeout [as _onTimeout] (/Users/jan/Developer/microservice/node_modules/mariadb/lib/pool.js:287:5)
at ontimeout (timers.js:486:15)
at tryOnTimeout (timers.js:317:5)
at Timer.listOnTimeout (timers.js:277:5)
(node:76515) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This errororiginated either by throwing inside of an async function without a catch block, or byrejecting a promise which was not handled with .catch(). (rejection id: 2)
(node:76515) [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.
I programmed in JS for last two years, but I'm new to Node.js and I thought it should work out of the box. Anyone?

The problem was that in phpMyAdmin I didn't added my home ip address so I can connect. For those who are just starting with it - you can create multiple users with the same name and password so you can actually have access from multiple IP's (like localhost, ::1 or 127.0.0.1 which is quite the same, but still required just for sure).
I have added additional user with same credentials pointing to my IP and it solved the problem.

For others with the same error message, particularly if the connection works the first few times but not after that, the error can happen if you don't end the connection with conn.end. Not OPs problem, but perhaps others.

For me the problem was solved by adding port: 3307 as another pool creation parameter.
Port 3306 seems to be default but some servers seem to prefer 3307.

Related

CockroachDB with node js pg driver

I am trying to connect CockroachDB and Nodes JS using the pg driver. I am able to establish a connection successfully, but every time when querying the tables: it works only when I prefix the table names with the database name, or otherwise It throws relation doesn't exist error. Though I am specifying the database name while establishing DB connection.
The code that I am using to establish DB connection :
var pg = require('pg');
var config = {
user: 'root',
host: 'localhost',
database: 'testDB',
port: 26257
};
var pool = new pg.Pool(config);
const client = await pool.connect();
Executing this line works fine as I prefix table name with DBname:
const response = await client.query('select * from testDB.test');
Executing this line raises the following error:
const response = await client.query('select * from test');
(node:12797) UnhandledPromiseRejectionWarning: error: relation "test" does not exist
at Parser.parseErrorMessage (/Users/naveenkumar/Ucars/node-cockroachDB/node_modules/pg-protocol/dist/parser.js:278:15)
at Parser.handlePacket (/Users/naveenkumar/Ucars/node-cockroachDB/node_modules/pg-protocol/dist/parser.js:126:29)
at Parser.parse (/Users/naveenkumar/Ucars/node-cockroachDB/node_modules/pg-protocol/dist/parser.js:39:38)
at Socket.<anonymous> (/Users/naveenkumar/Ucars/node-cockroachDB/node_modules/pg-protocol/dist/index.js:10:42)
at Socket.emit (events.js:314:20)
at addChunk (_stream_readable.js:304:12)
at readableAddChunk (_stream_readable.js:280:9)
at Socket.Readable.push (_stream_readable.js:219:10)
at TCP.onStreamRead (internal/stream_base_commons.js:188:23)
at TCP.callbackTrampoline (internal/async_hooks.js:123:14)
(Use `node --trace-warnings ...` to show where the warning was created)
<node_internals>/internal/process/warning.js:33
(node:12797) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)
<node_internals>/internal/process/warning.js:33
(node:12797) [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.
Any kind of help is appreciated, Thanks in advance :)
EDIT: The database name should be all lowercase. See https://www.cockroachlabs.com/docs/stable/keywords-and-identifiers.html#rules-for-identifiers
defaultdb> CREATE DATABASE TeSt;
CREATE DATABASE
Time: 166.382ms
defaultdb> SHOW DATABASES;
database_name | owner
-----------------------------+---------------------
defaultdb | root
test | lauren
testdb | lauren
With CockroachDB v20.2.2 and pg v8.5.1, I'm not able to reproduce the issue. The below works as expected:
const { Pool } = require("pg");
const config = {
...
database: "testdb",
...
};
const pool = new Pool(config);
;(async function() {
const client = await pool.connect();
await client.query("select * from test_table", (err, res) => {
console.log(err, res);
client.end();
});
})()

`newSession` not found when using local capabilities

I'm facing this error when trying to use BrowserStack local capability:
(node:67602) UnhandledPromiseRejectionWarning: UnsupportedOperationError: newSession: Not Found
at parseHttpResponse (/Users/ardo/Documents/workspace/test-browser-stack/node_modules/selenium-webdriver/lib/http.js:578:11)
at Executor.execute (/Users/ardo/Documents/workspace/test-browser-stack/node_modules/selenium-webdriver/lib/http.js:489:26)
at process._tickCallback (internal/process/next_tick.js:68:7)
(node:67602) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)
(node:67602) [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.
(node:67602) UnhandledPromiseRejectionWarning: UnsupportedOperationError: newSession: Not Found
at parseHttpResponse (/Users/ardo/Documents/workspace/test-browser-stack/node_modules/selenium-webdriver/lib/http.js:578:11)
at Executor.execute (/Users/ardo/Documents/workspace/test-browser-stack/node_modules/selenium-webdriver/lib/http.js:489:26)
at process._tickCallback (internal/process/next_tick.js:68:7)
(node:67602) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 3)
My code is pretty simple:
const webdriver = require('selenium-webdriver');
const browserstack = require('browserstack-local');
const runTestSuite = () => {
const capabilities = {
browserName: 'Chrome',
browser_version: '80.0 beta',
os: 'OS X',
os_version: 'Catalina',
resolution: '1024x768',
'browserstack.user': '<user>',
'browserstack.key': '<key>',
'browserstack.local': true,
'browserstack.localIdentifier': 'ardotest',
// 'browserstack.use_w3c': true,
acceptSslCerts: true,
name: 'Bstack-[Node] Sample Test-OS X Catalina-Chrome 80',
};
// https://www.browserstack.com/question/663
const driver = new webdriver.Builder()
.usingServer('http://localhost:3000') // tried using the IP that I got from Network settings on my machine, it spat out the same error
.withCapabilities(capabilities)
.build();
console.log('quit');
driver.quit();
};
// creates an instance of Local
const bsLocal = new browserstack.Local();
// replace <browserstack-accesskey> with your key. You can also set an environment variable - "BROWSERSTACK_ACCESS_KEY".
const bsLocalArgs = { key: '<browserstack-accesskey>' };
// https://github.com/browserstack/browserstack-local-nodejs/blob/master/lib/Local.js
// starts the Local instance with the required arguments
bsLocal.start(bsLocalArgs, function(err) {
if (err) {
console.error(err);
return;
}
if (!bsLocal.isRunning()) {
return;
}
try {
runTestSuite();
} catch (e) {
console.error(e);
} finally {
// stop the Local instance
bsLocal.stop(function(err) {
if (err) {
console.error(err);
}
console.log('===== BrowserStack tunnel stopped =====');
});
}
});
Versions:
"selenium-webdriver": "^4.0.0-alpha.5",
"browserstack-local": "^1.4.5",
My local environment:
"node": "10.16.3",
"npm": "6.8.0",
macOS 10.14.6
Looking through the code, it's clear that it's trying to hit /session url to create a new session or something. I'm not sure whether I should support /session manually, or I'm just missing something that's really stupid here?
It seems that BrowserStack provides it's own Hub URL for the test executions. You may try changing the hub URL from localhost:3000 to BrowserStacks hub url.
Referring to this code -> .usingServer('http://localhost:3000')
This document has more details: https://www.browserstack.com/local-testing/automate
You just need to make sure to have the same localIdentifier arg in both capabilities AND bsLocalArgs.
That is, both in .withCapabilities(<here>) and new browserstack.Local().start(<here>, ...)

bug in connection to cluster mongodb

i'm using nodejs to connect to mongodb and i get this error
i added the IP and nothing happend
(node:7412) UnhandledPromiseRejectionWarning: MongoNetworkError: connection 5 to cluster0-shard-00-02-xobf0.mongodb.net:27017 closed
at TLSSocket.<anonymous> (C:\Users\user\Desktop\NodeJS - The Complete Guide\node_modules\mongodb-core\lib\connection\connection.js:352:9)
at Object.onceWrapper (events.js:277:13)
at TLSSocket.emit (events.js:189:13)
at _handle.close (net.js:597:12)
at TCP.done (_tls_wrap.js:388:7)
(node:7412) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)
(node:7412) [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.
[nodemon] clean exit - waiting for changes before restart
Try this ,
const MongoClient = require("mongodb").MongoClient;
const uri ="mongodb+srv://user:userpassword#meanapp-srlw9.mongodb.net/test?retryWrites=true";
const client = new MongoClient(uri, { useNewUrlParser: true });
client.connect(err => {
const collection = client.db("test").collection("devices");
// perform actions on the collection object
console.log("connencted");
client.close();
});
For now, change your cluster setting to connect from anywhere

node-postgres reconnect when connection failed [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
This is my db connection code of nodejs project, in some situation my db is down (not working), i want to try reconnecting to db, but i don't know how to that, please help me
const { Client } = require('pg');
const postgis = new Client({
user: process.env.PGUSER,
host: process.env.PGHOST,
database: process.env.PGDATABASE,
password: process.env.PGPASSWORD,
port: process.env.PGPORT
});
console.log(`Connecting to PostGIS database ${process.env.PGDATABASE} on: ${process.env.PGHOST}:${process.env.PGPORT}`);
postgis.connect()
.then(() => {
console.log(`PostGIS connected to: ${process.env.PGDATABASE} on: ${process.env.PGHOST}:${process.env.PGPORT}`)
})
.catch((e) => {
// console.error(`PostGIS connection error: ${e}`)
setTimeout(function () {
console.log("entering again")
postgis.connect();
}, 10000);
});
error:
(node:10299) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)
(node:10299) [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.
You can handle it in catch block and reconnect to posgres
setTimeout(function () {
postgis.connect();
}, 10000);

mongodb replica set connection in Docker container

I have created a mongodb replica set in 3 virtualbox vms, manasger1, worker1, worker2. each replica set has it's own containers. The replica set works fine and I can login to the servers:
docker exec -it mongoNode1 bash -c 'mongo -u $MONGO_USER_ADMIN -p $MONGO_PASS_ADMIN --authenticationDatabase "admin"'
MongoDB shell version v3.6.4
connecting to: mongodb://127.0.0.1:27017
MongoDB server version: 3.6.4
Welcome to the MongoDB shell.
For interactive help, type "help".
For more comprehensive documentation, see
http://docs.mongodb.org/
Questions? Try the support group
http://groups.google.com/group/mongodb-user
rs1:PRIMARY> use medmart_db
switched to db medmart_db
rs1:PRIMARY> db.providers.findObe()
2018-05-14T17:46:38.844+0000 E QUERY [thread1] TypeError: db.providers.findObe is not a function :
#(shell):1:1
rs1:PRIMARY> db.providers.findOne()
{
"_id" : ObjectId("56ddb50c230e405eafaf7781"),
"provider_id" : 6829973073,
When I run my nodejs application it connects to the replica set. The problem is that when I create a container for my application I get the following exception, my container stops, and I can no longer connect to the replica set PRIMARY, but instead to the secondary.
(node:16) UnhandledPromiseRejectionWarning: MongoNetworkError: failed to connect to server [worker2:27017] on first connect [MongoNetworkError: connection 5 to worker2:27017 timed out]
at Pool.<anonymous> (/home/nupp/app/node_modules/mongoose/node_modules/mongodb-core/lib/topologies/server.js:505:11)
at Pool.emit (events.js:182:13)
at Connection.<anonymous> (/home/nupp/app/node_modules/mongoose/node_modules/mongodb-core/lib/connection/pool.js:329:12)
at Object.onceWrapper (events.js:273:13)
at Connection.emit (events.js:182:13)
at Socket.<anonymous> (/home/nupp/app/node_modules/mongoose/node_modules/mongodb-core/lib/connection/connection.js:256:10)
at Object.onceWrapper (events.js:273:13)
at Socket.emit (events.js:182:13)
at Socket._onTimeout (net.js:447:8)
at ontimeout (timers.js:427:11)
at tryOnTimeout (timers.js:289:5)
at listOnTimeout (timers.js:252:5)
at Timer.processTimers (timers.js:212:10)
(node:16) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)
(node:16) [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.
I opened an issue ticket with mongoose for help but their solution doesn't work (they asked that I change from ip address to domain name but I still get the same error).
My connection module is:
'use strict';
const mongoose = require('mongoose');
const getURL = (options) => {
const url = options.servers.reduce((accumulator, current) => {
accumulator += current+',';
return accumulator;
},`mongodb://${options.user}:${options.pass}#`);
return `${url.substr(0,url.length-1)}/${options.db}?replicaSet=${options.repl}&authSource=admin`;
}
const connect = (config, mediator) => {
mediator.once('boot.ready', () => {
const options = {
native_parser: true,
poolSize: 5,
user: config.user,
pass: config.pass,
promiseLibrary: global.Promise,
autoIndex: false,
reconnectTries: 30,
reconnectInterval: 500,
bufferMaxEntries: 0,
connectWithNoPrimary: true ,
readPreference: 'ReadPreference.SECONDARY_PREFERRED',
};
mongoose.connect(getURL(config), options);
mongoose.connection.on('error', (err) => {
mediator.emit('db.error', err);
});
mongoose.connection.on('connected', () => {
mediator.emit('db.ready', mongoose);
});
});
};
module.exports = Object.assign({},{connect});
My config file is:
'use strict';
const serverConfig = {
port: 3000,
};
const dbConfig = {
db: 'xxxxxxx',
user: 'xxxxxx',
pass: 'xxxxxxx',
repl: 'rs1',
servers: (process.env.DB_SERVERS) ? process.env.DB_SERVERS.split(' ') : ['192.168.99.100:27017','192.168.99.101:27017','192.168.99.102:27017'],
};
module.exports = Object.assign({},{dbConfig, serverConfig});
So there are a couple of steps to resolving this issue. First and foremost is the fact that hosts file on the virtualBox machines must be updated to have the ip addresses of mongodb domains. To do that:
> docker-machine ssh manager1
docker#manager1:~$ sudo vi /etc/hosts
#add the following
192.168.99.100 manager1
192.168.99.101 worker1
192.168.99.102 worker2
Repeat for worker1 and worker2.
If by adding the following you are good, then skip the second part.
Next, if you get the following error:
Error: ERROR::providers-service::model::ProviderModel::getProviderById: TypeError: Cannot read property 'wireProtocolHandler' of null
at cb (/home/nupp/app/src/model/ProviderModel.js:182:13)
at /home/nupp/app/node_modules/mongoose/lib/model.js:4161:16
at Immediate.Query.base.findOne.call (/home/nupp/app/node_modules/mongoose/lib/query.js:1529:14)
at Immediate.<anonymous> (/home/nupp/app/node_modules/mquery/lib/utils.js:119:16)
at runCallback (timers.js:696:18)
at tryOnImmediate (timers.js:667:5)
at processImmediate (timers.js:649:5)
Remove any options to mongoose.connect. Here's how mine looks now:
mediator.once('boot.ready', () => {
const options = {};
mongoose.connect(getURL(config), options);
mongoose.connection.on('error', (err) => {
mediator.emit('db.error', err);
});
mongoose.connection.on('connected', () => {
mediator.emit('db.ready', mongoose);
});
});
Hope my solution can help someone else. Took me a few long days to finally figure this out.

Resources