I am using the following code snippet in a Node.js application to attempt to query a (local) postgres database:
var conString = "postgres://user:password#localhost:5432/mydatabase";
var client = new pg.Client(conString);
client.connect(function(err) {
if(err) {
return console.error('could not connect to postgres', err);
}
client.query("SELECT * FROM users WHERE name = $1 AND cred = $2", [String(req.body.usr), String(req.body.pword)], function(err, result) {
if(err) {
return console.error('error running query', err);
}
if (typeof result.rows[0] === "undefined") {
console.log("No user/password determined in DB for login attempt");
} else {
} //user/password is 'undefined' (NOT found in database)...OR NOT...
client.end();
});
});
I am receiving an error when the query runs...I believe the problem may possibly be the number of parameters in my query call...? If that is the case (or it is some other syntax problem) could anybody be so kind to inform how I should change the code to perform the query correctly...?
I simply need to take 2 (user-supplied) results from a form (req.body.usr and req.body.pword) and compare them to the database table 'users' to determine if the credentials are correct. I already believe the database connection works properly. Any advice greatly appreciated. I thank you in advance.
Change:
client.query("SELECT * FROM users WHERE name = $1 AND cred = $2", [String(req.body.usr), String(req.body.pword)], function(err, result) {...
to:
const query = {
text: "SELECT * FROM users WHERE name = $1 AND cred = $2",
values: [String(req.body.usr), String(req.body.pword)]
};
client.query(query, function(err, result) {
Read more: https://node-postgres.com/features/queries
Related
My code is in Nodejs backend below
app.get('/room_selected', function (req, res){
var clientID = 'a#gmail.com';
var room = 'Room 1';
var query = connection.query ('SELECT clientID FROM clientDevices WHERE deviceName = ?', [room],
function (err, rows, fields){
if (err) throw err;
return rows[0].clientID;
});
console.log (query);
if (clientID == query){
res.status(400).json ('success');
} else {
res.status(400).json('The selected room does not have a device attached');
}
});
When I print console.log(query), it returns [ { clientID: 'a#gmail.com' } ].
I want to return only a#gmail.com. Could you guys know how to figure out it? since I want it to compare with clientID to print out the success message, however, it printed out The selected room does not have a device attached
Please help. Thank you
In your code, you didn't wait for the query to be executed. Following is the code which will give a response only after the query is executed.
And also success should not have a status code of 400 so I have removed that which will give a status code of 200
app.get('/room_selected', function (req, res){
var clientID = 'a#gmail.com';
var room = 'Room 1';
var query = connection.query ('SELECT clientID FROM clientDevices WHERE deviceName = ?', [room],
function (err, rows, fields){
if (err) throw err;
if (rows.length && clientID == rows[0].clientID){
res.json('success');
} else {
res.status(400).json('The selected room does not have a device attached');
}
});
});
As the title reads, I am receiving a "query values must be an array" error when writing Node.js code to attempt to query a local (postgres) database. Here is the code I am using:
var pg = require('pg');
var conString = "postgres://user:pass#localhost:5432/mydatabase";
var client = new pg.Client(conString);
client.connect(function(err) {
if(err) {
return console.error('could not connect to postgres', err);
}
client.query('SELECT $1::text AS name', 'howdy', function(err, result) {
if(err) {
return console.error('error running query', err);
}
console.log(result.rows[0].name);
client.end();
});
});
I believe this refers to the need to have the query string use array values rather than a direct string...however I am unsure how to structure the code. Any advice would be greatly appreciated. I thank you in advance. Regards.
The error is right. The second parameter to query should be an array. This is a paramterized query
client.query('SELECT $1::text AS name', ['howdy'] ...
I was wondering if there is a way I can get a part of an object in mongo using node. For example, it would be great if I could log say the email that is being added, by using something like console.log(result.email) to get the email part of my response. Does anyone know how to do this?
Ok so I have found a way to do this. It will not work on the .find function for some reason, but will work on .findOne and .sort
MongoClient.connect(url, function(err, db) {
if (err) throw err;
var dbo = db.db("db");
let query = {
username: "username",
key: "key"
};
dbo.collection("keys").findOne(query, (function(err, result) {
var lengthboi = result.length;
console.log(result)
if (lengthboi === 1) {
//do stuff
} else {
}
}));
});
I am trying to allow a user to input criteria (i.e. Client) for my application to query a mySQL database and return all matching results. My connection is established and I am able to hardcode my query (connection.query("select * from ACHLookerUpper where Client = ?", ["ex."]) and return expected results. I can also simply run the Prompt command and intake and console.log my input.
However, when I try to combine the two -- intake user input via Prompt and query -- I cannot successfully pass input into my query. I am somewhat new to node so I'm sure there's an issue in my nesting, however the error is not very helpful other than telling me "Cannot enqeue Query after invoking Quit".
I'm sure I need to store results.Client as a var or param then call it in my query but can't figure out how.
var mysql = require("mysql");
var prompt = require('prompt');
var connection = mysql.createConnection({
host: "<host>",
user: "<user>",
password: "<pw>",
database: "<db>",
port: "<port>"
});
connection.connect(function(err){
if(err){
console.log('Error connecting to Db');
return;
}
});
prompt.start();
prompt.get(['Client'], function (err, result) {
if (err) { console.log("Error");
return;
};
connection.query("select * from ACHLookerUpper where Client = ?", [result.Client], exports.MyHandler = function(err, rows){
if (err) {
console.log(err);
return;
}
rows.forEach(function(result) {
console.log(result.ID, result.Name, result.Client, result.ACH);
})
})
});
connection.end(function(err) {
});
prompt.get() is asynchronous, so connection.end() is getting called first and then later on you try to execute the query when input has been received for the prompt, but the connection has already ended at that point.
I'm using nodejs with MySQL for the first time , I'm struggling to properly preparing statements ,I have no problems when writing and executing some insertion statements but when i tried to write the selection statements i can't know what is the correct syntax .I can't find tutorial for the beginner
This is the selection code
io.sockets.on('connection', function(client) {
client.on('check_id', function(login_feilds) {
console.log(login_feilds);
var login_feilds_as_json = login_feilds ,
Email = login_feilds_as_json.email ,
password = login_feilds_as_json.password ;
var sql = "SELECT * FROM ?? WHERE ?? = ? AND ?? = ?";
var inserts = ['users', 'email', Email,'password',password];
sql = mysql.format(sql, inserts);
console.log(sql);
connection.query( sql , function(err, rows){
if(error){
console.log(error.message);
}else{
console.log('found it'); };
});
});
});
when I run the above code I got this
{ email: 'user#windowslive.com', password: 'user' }
SELECT * FROM `users` WHERE `email` = 'user#windowslive.com' AND `password` =
'user'
C:\Users\jiil\Desktop\our-project\node_modules\mysql\lib\protocol\Parser.js:82
throw err;
^
ReferenceError: error is not defined
could you help me to figure out what i have to do or give me any good resources' links .
The problem is that you wrongly use variable name in your callback function. You need to change error to err.
connection.query(sql, function(err, rows){
if (err) {
console.log(err.message);
} else {
console.log('found it');
}
});
Hope it will be useful for you.