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'] ...
Related
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
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 am using mongodb driver for nodejs.
I am getting below error while updating a record.
{"name":"MongoError","message":"selector must be a valid JavaScript
object","driver":true}
Here is my script :
MongoClient.connect(url, function (err, db) {
if (err)
{
console.log('Unable to connect to the mongoDB server. Error:', err);
return;
}
var collName = "bank";
var SelectParas = {"name":"ABC"};
var UpdateValues = {"name":"PQR"};
db.collection(collName).update(collName,SelectParas,{$set:UpdateValues},function (err,numUpdated){
if(err)
{
console.log('err');
console.log(err);
return;
}
if(numUpdated)
{
console.log('Updated Successfully %d document(s).', numUpdated);
}
db.close();
});
});
I can write the below line in mongo console & it works.
db.bank.update({"name":"ABC"},{$set:{"name":"PQR"}})
You are passing collecion name i.e. a string as find query of the update. Need not pass collecton name there.
db.collection(collName).update(collName,SelectParas,{$set:UpdateValues},function (err,numUpdated)
// collName need not pass in the update function.
Need to use
db.collection(collName).update(SelectParas,{$set:UpdateValues},function (err,numUpdated) instead.
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.
I am new to node.js and was wondering why my code always return null.
I have db.js
exports.getItems = function(){
var conn = mysql.createConnection();
conn.connect();
conn.query("Select * From Items", function(err, rows, fields) {
if (err) throw err;
conn.end();
return rows;
});
};
and the module is called like this:
var db = require('../db.js');
exports.items = function(req, res){
var data = db.getItems();
console.log('second', data);
res.end(data);
};
and route:
app.get('/api/items', api.items);
The console.log('second') is always "second undefined". I have verified that the query is return items in the rows.
Please advice.
Classic async problem.
getItems is going to return before the database query is done. The data from the database is returned in the callback, not in the function itself.
When you write:
var data = db.getItems();
console.log('second', data);
res.end(data);
the value for data is undefined because you don't have a return statement inside getItems! So getItems returns undefined, as per the rules of JavaScript.
What you need is something like (and please understand I have not tested this) is:
exports.items = function(req, res){
var conn = mysql.createConnection();
conn.connect();
conn.query("Select * From Items", function(err, rows, fields) {
conn.end();
if (err) throw err;
res.end(rows);
});
}
See various sites online for managing connections cleanly. But this should be enough to get you to understand that the response should be sent from the callback of query which is where the data is actually available.