I am trying to add a PostgreSQL database to my existing nodejs project on heroku. I am having trouble accessing the local version of the database at all, and also having trouble writing to the heroku database.
Here is part of the code that I have tried:
const { Client } = require('pg');
const client = new Client({
connectionString: process.env.DATABASE_URL,
ssl: true,
});
client.connect();
// client
let qu = 'SELECT table_schema,table_name FROM information_schema.tables;';
//qu = 'CREATE TABLE test (name varchar(40));';
//qu = 'SELECT * FROM test;';
// qu = 'INSERT INTO test name VALUES("testasdf");';
// qu = 'CREATE DATABASE X
client.query(qu, (err, res) => {
//console.log("trying");
if (err) throw err;
for (let row of res.rows) {
console.log(JSON.stringify(row));
}
client.end();
});
I have tried following the instructions here: https://devcenter.heroku.com/articles/heroku-postgresql
but I can't access the local database or do anything to the remote one.
Here is the local error message:
(node:8402) UnhandledPromiseRejectionWarning: error: password authentication failed for user "..."
at Connection.parseE (.../theland/node_modules/pg/lib/connection.js:553:11)
at Connection.parseMessage (.../theland/node_modules/pg/lib/connection.js:378:19)
at TLSSocket. (.../theland/node_modules/pg/lib/connection.js:119:22)
at emitOne (events.js:116:13)
at TLSSocket.emit (events.js:211:7)
at addChunk (_stream_readable.js:263:12)
at readableAddChunk (_stream_readable.js:250:11)
at TLSSocket.Readable.push (_stream_readable.js:208:10)
at TLSWrap.onread (net.js:597:20)
(node:8402) 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:8402) [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 don't know how to create a table on the remote one.
I am running on Linux with
node-v = 8.11.2
npm-v = 6.1.0
pg: ^7.4.3
I am using psql too, no GUI.
Thanks for the help.
EDIT---
Where should I add the authentication? Do I need to take the script off of github if I add the authentication and don't want people to be able to be admins for my database?
password authentication failed for user "..."
Obviously you are not using the right password for the user. The positive news is that there is a server responding your request.
Unhandled promise rejection
There is an error, probably thrown here:
if (err) throw err;
You seem not to catch it somewhere, you only throw it. Try to put it into some try-catch-block, e.g. like
function queryDatabase() {
try {
const client = new Client({
connectionString: process.env.DATABASE_URL,
ssl: true,
});
client.connect();
// client
let qu = 'SELECT table_schema,table_name FROM information_schema.tables;';
//qu = 'CREATE TABLE test (name varchar(40));';
//qu = 'SELECT * FROM test;';
// qu = 'INSERT INTO test name VALUES("testasdf");';
// qu = 'CREATE DATABASE X
client.query(qu, (err, res) => {
//console.log("trying");
if (err) throw err;
for (let row of res.rows) {
console.log(JSON.stringify(row));
}
client.end();
});
} catch (error) {
// if you need further help, remember to provide this error here.
console.log(error);
}
}
Related
So I'm new to node.js and I'm trying to make a connection to my local database to later insert data.
However when I execute my code it gives me a connection error with errorcode ESOCKET. I tried different ways to structure my connectionstring but it always gives me this error.
As I said I'm new to nodejs so I'm not really sure if the problem is my connection string or the port it uses (1433) or something entirely different.
code:
const sql = require('mssql');
const config = {
user: 'test',
password: 'test',
server: '.',
database: 'Parkings'
}
async function databaseconn(parking){
try{
let pool = await sql.connect(config);
await pool.request().query(`
if not exists (select 1 from [Parking] where [Name] = '${parking.name}')
begin
insert into Parking ([Name], [Type], [Latitude], [Longtitude], [MaxCap])
values ('${parking._name}', '${parking._type}', ${parking._latitude}, ${parking._longitude}, ${parking._maxcap})
end
`);
await pool.request().query(`
insert into [Entry] ([TimeDay], [Available], [ParkingId])
values (${p._time}, ${p._available}, (select Id from Parking where Name = '${p._name}'))
`);
pool.close();
} catch (err){
console.log(err);
}
}
error:
ConnectionError: Failed to connect to .:1433 - getaddrinfo ENOTFOUND .
at Connection.<anonymous> (D:\Documenten\2019-2020\ParkingProject\nodejs_serverapp\node_modules\mssql\lib\tedious\connection-pool.js:68:17)
at Object.onceWrapper (events.js:428:26)
at Connection.emit (events.js:321:20)
at Connection.socketError (D:\Documenten\2019-2020\ParkingProject\nodejs_serverapp\node_modules\tedious\lib\connection.js:1290:12)
at D:\Documenten\2019-2020\ParkingProject\nodejs_serverapp\node_modules\tedious\lib\connection.js:1116:21
at GetAddrInfoReqWrap.callback (D:\Documenten\2019-2020\ParkingProject\nodejs_serverapp\node_modules\tedious\lib\connector.js:158:16)
at GetAddrInfoReqWrap.onlookupall [as oncomplete] (dns.js:76:17) {
code: 'ESOCKET',
originalError: ConnectionError: Failed to connect to .:1433 - getaddrinfo ENOTFOUND .
at ConnectionError (D:\Documenten\2019-2020\ParkingProject\nodejs_serverapp\node_modules\tedious\lib\errors.js:13:12)
at Connection.socketError (D:\Documenten\2019-2020\ParkingProject\nodejs_serverapp\node_modules\tedious\lib\connection.js:1290:56)
at D:\Documenten\2019-2020\ParkingProject\nodejs_serverapp\node_modules\tedious\lib\connection.js:1116:21
at GetAddrInfoReqWrap.callback (D:\Documenten\2019-2020\ParkingProject\nodejs_serverapp\node_modules\tedious\lib\connector.js:158:16)
at GetAddrInfoReqWrap.onlookupall [as oncomplete] (dns.js:76:17) {
message: 'Failed to connect to .:1433 - getaddrinfo ENOTFOUND .',
code: 'ESOCKET'
},
name: 'ConnectionError'
}
picture
SOLUTION
after a lot of trouble I fount the sollution to the issue thanks to a github post. You have to enable the TCP/IP protocol on your sql server and restart it. Guide in links below:
https://github.com/tediousjs/tedious/issues/799
https://www.blackbaud.com/files/support/infinityinstaller/content/installermaster/tkenablenamedpipesandtcpipconnections.htm
I'm making a slack clone with socket.io and node with a mongodb cluster. everything worked fine this weekend until today when i opened the project and noticed a message I've never seen before:
(node:31352) UnhandledPromiseRejectionWarning: FetchError: request to http://localhost:5000/chat failed, reason: getaddrinfo ENOTFOUND localhost
at ClientRequest. (/Users/philiplagergrenydehed/git/slack-clone/slack-clone/node_modules/node-fetch/lib/index.js:1455:11)
at ClientRequest.emit (events.js:219:5)
at Socket.socketErrorListener (_http_client.js:420:9)
at Socket.emit (events.js:219:5)
at emitErrorNT (internal/streams/destroy.js:84:8)
at processTicksAndRejections (internal/process/task_queues.js:84:21)
(node:31352) 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: 2)
What does this mean and how do i fix it?
This is my fetch but I cannot see anything wrong with it.
router.post('/new', function (req, res, next) {
console.log(req.body)
const messageObject = {
channelID: '437469384738473894',
name: req.body.name,
time: req.body.time,
text: req.body.message
}
const option = {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify(messageObject)
};
try{
fetch('http://localhost:5000/chat', option)
.then(response => {
response.json()
.then(function(data){
response.send(data)
});
});
} catch{
res.send("error")
}
})
I'm stuck and I really need your help!!
I am getting this error when i am trying to insert anything into Mongo db. Any help would be appreciated.
const mongoose = require('mongoose');
const dbpath = "mongodb+srv://cluster0-bm7js.mongodb.net/classic";
mongoose.connect(dbpath, {useUnifiedTopology: true , useNewUrlParser: true })
.then(()=> console.log("Now connected to MongoDB!"))
.catch(err=> console.error("Something went wrong", err));
const gameSchema = new mongoose.Schema( {
title: String,
publisher: String,
tags: [String],
date: {
type: Date,
default: Date.now
},
onSale: Boolean,
price: Number
});
const Game = mongoose.model('Game', gameSchema);
async function saveGame() {
const game = new Game( {
title: "Tekken 3",
publisher: "Neogeo",
tags: ["adventure", "action"],
onSale: false,
price: 69.99,
});
const result = await game.save();
console.log(result);
}
saveGame();
This is my code and the error i am getting after running the above code is as,
(node:94819) UnhandledPromiseRejectionWarning: MongoError: user is not allowed to do action [insert] on [classic.games]
at Connection.<anonymous> (/Users/thinkun/Desktop/mongo/node_modules/mongodb/lib/core/connection/pool.js:466:61)
at Connection.emit (events.js:198:13)
at processMessage (/Users/thinkun/Desktop/mongo/node_modules/mongodb/lib/core/connection/connection.js:364:10)
at TLSSocket.<anonymous> (/Users/thinkun/Desktop/mongo/node_modules/mongodb/lib/core/connection/connection.js:533:15)
at TLSSocket.emit (events.js:198:13)
at addChunk (_stream_readable.js:288:12)
at readableAddChunk (_stream_readable.js:269:11)
at TLSSocket.Readable.push (_stream_readable.js:224:10)
at TLSWrap.onStreamRead [as onread] (internal/stream_base_commons.js:94:17)
(node:94819) 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:94819) [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.
Not sure why Mongo db is unable to help me working inside.
Thanks in advance.
const mongoose = require('mongoose');
const dbpath = "mongodb+srv://cluster0-xxxx.mongodb.net/Game";
mongoose.connect(dbpath, {user: 'username', pass: 'password'})
.then(()=> console.log("Now connected to MongoDB!"))
.catch(err=> console.error("Something went wrong", err));
There was an issue with Connection string. All sorted with username and password.
I am getting this JavaScript error:
TypeError: Cannot read property 'title' of null
Here is the code:
Mds-iMac:cmscart imac$ nodemon app
[nodemon] 1.11.0
[nodemon] to restart at any time, enter rs
[nodemon] watching: .
[nodemon] starting node app app.js
(node:2274) DeprecationWarning: open() is deprecated in mongoose >= 4.11.0, use openUri() instead, or set the useMongoClient option if using connect() or createConnection(). See http://mongoosejs.com/docs/4.x/docs/connections.html#use-mongo-client
(node:2274) DeprecationWarning: Mongoose: mpromise (mongoose's default promise library) is deprecated, plug in your own promise library instead: http://mongoosejs.com/docs/promises.html
Server started on port 3200
Db.prototype.authenticate method will no longer be available in the next major release 3.x as MongoDB 3.6 will only allow auth against users in the admin db and will no longer allow multiple credentials on a socket. Please authenticate using MongoClient.connect with auth credentials.
Connected to MongoDB
events.js:182
throw er; // Unhandled 'error' event
^
TypeError: Cannot read property 'title' of null
at /Users/imac/Desktop/cmscart/routes/pages.js:17:24
at model.Query.<anonymous> (/Users/imac/Desktop/cmscart/node_modules/mongoose/lib/model.js:4074:16)
at /Users/imac/Desktop/cmscart/node_modules/kareem/index.js:273:21
at /Users/imac/Desktop/cmscart/node_modules/kareem/index.js:131:16
at _combinedTickCallback (internal/process/next_tick.js:131:7)
at process._tickCallback (internal/process/next_tick.js:180:9)
[nodemon] app crashed - waiting for file changes before starting...
The page.js code is:
var express = require('express');
var router = express.Router();
// Get Page model
var Page = require('../models/page');
/*
* GET /
*/
router.get('/', function (req, res) {
Page.findOne({slug: 'home'}, function (err, page) {
if (err)
console.log(err);
res.render('index', {
title: page.title,
content: page.content
});
});
});
/*
* GET a page
*/
router.get('/:slug', function (req, res) {
var slug = req.params.slug;
Page.findOne({slug: slug}, function (err, page) {
if (err)
console.log(err);
if (!page) {
res.redirect('/');
} else {
res.render('index', {
title: page.title,
content: page.content
});
}
});
});
// Exports
module.exports = router;
The error is occuring inside the JavaScript functions at title: page.title, above.
Please help me out.
router.get('/edit-page/:slug', (req, res) => {
Page.findOne({slug : req.params.slug}).then((page) => {
if(!page) { //if page not exist in db
return res.status(404).send('Page not found');
}
res.render('admin/edit_page', { //page exist
title: page.title,
slug: page.slug,
content: page.content,
id: page._id
});
}).catch((e) => {//bad request
res.status(400).send(e);
});
});
Use this code it will work the logic is same but i have handled the conditions using promises it definitely worked for me. Hope it helps you :)
It means that when
function (err, page) {
was called, inside of Page.findOne, the page argument did not have a property of title.
(without context of how Page.findOne is being used, hard to say how to fix it)
if (err)
console.log(err);
Is one issue. When you get an error you should return an http error then exit the function eg:
if (err) {
console.log(err);
res.statusCode = 500;
res.end('error');
}
When there is an error the page variable will be null, which explains the exception thrown.
after I started server at port 27017, opened another window and run my server program it is showing the connection error as follow
C:\node-mongodb\node_modules\mongodb\lib\server.js:242
process.nextTick(function() { throw err; })
^
AssertionError: { [MongoError: connect UNKNOWN 127.0.0.1:27017 -
Local(undefined:undefined)]
name: 'MongoError',
message: 'connect UNKNOWN == null
at C:\node-mongodb\simple-server.js:8:12
at C:\node-mongodb\node_modules\mongodb\lib\mongo_client.js:330:20
at C:\node-mongodb\node_modules\mongodb\lib\db.js:231:14
at null.<anonymous> (C:\node-mongodb\node_modules\mongodb\lib\server.js:240:9)
at g (events.js:260:16)
at emitTwo (events.js:87:13)
at emit (events.js:172:7)
at null.<anonymous(C:\nodemongodb\node_modules\mongodb\node_modules\mongo
db-core\lib\topologies\server.js:218:12)
at g (events.js:260:16)
at emitTwo (events.js:87:13)
I tried removing lock file repairing mongodb and other solutions that are given for other similar questions but they are not working.
please tell my why this error is coming and how I can resolve it.
I am running on windows xp(32-bit).
This is the simple-server.js file:
var MongoClient = require('mongodb').MongoClient,
assert = require('assert');
// Connection URL
var url = 'mongodb://localhost:27017/test';
// Use connect method to connect to the Server
MongoClient.connect(url, function (err, db) {
assert.equal(err,null);
console.log("Connected correctly to server");
var collection = db.collection("dishes");
collection.insertOne({name: "nerd21", description: "test"},
function(err,result){
assert.equal(err,null);
console.log("After Insert:");
console.log(result.ops);
collection.find({}).toArray(function(err,docs){
assert.equal(err,null);
console.log("Found:");
console.log(docs);
db.dropCollection("dishes", function(err, result){
assert.equal(err,null);
db.close();
});
});
});
});
screenshot of command prompt is as follows:enter image description here