CockroachDB with node js pg driver - node.js

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();
});
})()

Related

Unsure how to connect an api using nodejs

I'm trying to connect the openai api into my app but I'm not sure why it's not working. From my frontend, I have a createUserData that receives an input and then stores it to my MongoDB database. But now, I want to send that input that I received to the openai API and get a response based on what they said. I tried implementing it here but it crashed on me with this error:
UnhandledPromiseRejectionWarning: Error: Request failed with status code 401
at createError (C:\Users\simer\Downloads\Talkhappi\server\node_modules\axios\lib\core\createError.js:16:15)
at settle (C:\Users\simer\Downloads\Talkhappi\server\node_modules\axios\lib\core\settle.js:17:12)
at IncomingMessage.handleStreamEnd (C:\Users\simer\Downloads\Talkhappi\server\node_modules\axios\lib\adapters\http.js:322:11)
at IncomingMessage.emit (events.js:387:35)
at endReadableNT (internal/streams/readable.js:1317:12)
at processTicksAndRejections (internal/process/task_queues.js:82:21)
(Use `node --trace-warnings ...` to show where the warning was created)
(node:17844) 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: 2)
(node:17844) [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.
For some reason I crash when I try and call this API, am I doing it wrong?
Right now I just want to log whatever the response I get from the API, once I'm able to do that then I will store it to the database as well. But I can't even log it as I get an error. Here is my code:
const { Configuration, OpenAIApi } = require("openai");
// create new user data
const createUserData = async (req, res) => {
const {id, scores, transcript} = req.body
const user_id = req.user._id
console.log(user_id)
const configuration = new Configuration({
apiKey: process.env.OPENAI_API_KEY,
});
const openai = new OpenAIApi(configuration);
const response = await openai.createCompletion({
model: "text-davinci-002",
prompt: "Provide personal feedback for me and give me tips: " + transcript,
temperature: 0.7,
max_tokens: 256,
top_p: 1,
frequency_penalty: 0,
presence_penalty: 0,
});
console.log(response)
const newUserData = new UserData({
id: id,
scores: scores,
transcript: transcript,
user_id: user_id
})
// add doc to db
try {
await newUserData.save()
} catch (error) {
res.status(400).json({error: error.message})
}
console.log('POST:', newUserData)
return res.status(201).json({user_data: newUserData})
}

I get Parser.parseErrorMessage when inserting or updating in postgres

i'm having a headache with this cause i can't understand what's the problem.
This is my code in Express
router.patch("/:id", verifyToken, async (req, res) => {
const { id } = req.params;
const { title, content, categories } = req.body;
const authorId = parseInt(req.user.id);
try {
let postId = parseInt(id);
if (postId < 0)
res.json(
utils.generateError("Something went wrong, try to reload the page.")
);
//Validate post data
const { error } = validatePostData({
title,
content,
});
//Is there and error? Let the user know it.
if (error)
res.status(400).json(utils.generateError(error.details[0].message));
const slug = await utils.generateSlug(title);
const summary = await utils.extractSummary(content, 240);
const foundImage = await content.match(/!\[.*?\]\((.*?)\)/);
let image = "";
if (foundImage) image = foundImage[1];
const result = await pool.query(
"UPDATE posts SET title=$1, slug=$2, summary=$3, content=$4, image=$5, author=$6, categories=$7 WHERE id=$8",
[title, slug, summary, content, image, authorId, categories, postId]
);
if (result) res.json(result.rows[0]);
else throw "Error on updating result";
} catch (e) {
console.log(e);
res.json(utils.generateError("Something went wrong, try again."));
}
});
But when i make a patch request i get this in the console.
(node:20756) UnhandledPromiseRejectionWarning: error: invalid input syntax for integer: "NaN"
at Parser.parseErrorMessage (/Users/jcmunguia/Desktop/readalot-app/node_modules/pg-protocol/dist/parser.js:278:15)
at Parser.handlePacket (/Users/jcmunguia/Desktop/readalot-app/node_modules/pg-protocol/dist/parser.js:126:29)
at Parser.parse (/Users/jcmunguia/Desktop/readalot-app/node_modules/pg-protocol/dist/parser.js:39:38)
at Socket.<anonymous> (/Users/jcmunguia/Desktop/readalot-app/node_modules/pg-protocol/dist/index.js:8:42)
at Socket.emit (events.js:310:20)
at addChunk (_stream_readable.js:286:12)
at readableAddChunk (_stream_readable.js:268:9)
at Socket.Readable.push (_stream_readable.js:209:10)
at TCP.onStreamRead (internal/stream_base_commons.js:186:23)
(node:20756) 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:20756) [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'm using Postgres and pg for node to handle the database, the strange part is that the row is updated in the db but the result of the query doesn't return anything but that error.
Can anyone help me solve this?

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

Can't connect Node.js to remote database MariaDB

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.

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