Using an array in where clause with node-mysql - node.js

I want to do a query that would look like this :
"Select * FROM ... WHERE name in ?" which would be equal to
"Select * FROM ... WHERE name in 'joe','william', ..."
Would there be a way to do something like that?
Model.query(query, array, function(err, result) {...});
I tried the following :
string = array.join("','")
Model.query(query, string, function(err, result) {...});
But then here is the result I have (the backslashes appear due to the single quotes):
Select * FROM ... WHERE name in \'joe\',\'william\',..."

Simple queries
As #Raphael mentioned, for simple queries you can use Model.find(), relevant docs section.
Queries with join
For queries involving joins, you can use find.populate(), docs for populate. Example:
Model.find().where({
attr : [your array]
}).populate('association').exec(your callback);
Very complicated queries
For more complicated queries where not even populate is enough you can indeed use .query() (documentation) but I think you may have gotten the syntax wrong. The second argument is an array. Example:
var title = "The King's Speech";
Movie.query('SELECT * FROM movie WHERE title = $1', [title], function(err, results) {})

If you are using Waterline (it should be the case if your are creating a sails app) just do:
Model.find().where({
attr : [your array]
}).exec(your callback);

Related

Postgres Node search query using LIKE, how to set %

I have a weird problem I encountered using Postgresql and Node. I would like to use LIKE in my query together with % at the beginning and end of searched term. I have no issue using it in the plain SQL:
THIS WORKS:
SELECT * FROM vehicle WHERE module_imei LIKE '%searchterm%' OR custom_id LIKE '%searchterm%'
However, using it in Node is a bit of challenge. I haven't been successful in resolving it yet:
THIS DOES NOT WORK:
getVehiclesSearch: async function({ search }) {
let response;
try {
response = await pool.query(`SELECT * FROM vehicle WHERE module_imei LIKE %$1% OR custom_id LIKE %$1%`, [search]);
if(response) return response.rows;
} catch(error) {
// handle error
console.error(error);
// do not throw anything
}
},
Doing above will produce: syntax error at or near "%"
SELECT * FROM vehicle WHERE module_imei LIKE '%${$1}%' OR custom_id LIKE '%${$1}%
Doing above will produce: $1 is not defined
SELECT * FROM vehicle WHERE module_imei LIKE '%$1%' OR custom_id LIKE '%$1%'
Doing above will produce: bind message supplies 1 parameters, but prepared statement "" requires 0
I kind of struggle factoring the % in so it won't crash the query. Simply run out of ideas after trying above and variables of those. Thanks for your kind help.
This has been already answered over here:
Go postgresql LIKE query
In this particular case:
response = await pool.query(`SELECT * FROM vehicle WHERE module_imei LIKE '%'||$1||'%' OR custom_id LIKE '%'||$1||'%'`, [search]);
This would work.
You are missing single quotes, also I don't recognize a db adapter you use, but you can use template literals (watch out for sql injection!!!)
response = await pool.query(`SELECT * FROM vehicle WHERE module_imei LIKE '%${search}%' OR custom_id LIKE '%${search}%'`);

PostgreSQL REST API Node.js CRUD - String query parameter giving error

I am setting up my first REST API to query a Postgres database I set up. I have two CRUD methods that currently work that query for all rows in a table and for rows where ID = something, respectively.
The problem I'm having occurs when trying to query when the request parameter is a String. Here is the error I'm getting:
error: invalid input syntax for type integer: "NaN"
Here is how I've set up my GET route and endpoint URL:
const getShowByTitle = (request, response) => {
const title = request.params.title
pool.query('SELECT * FROM show WHERE title = $1', [title], (error, results) => {
if (error) {
throw error
}
response.status(200).json(results.rows)
})
}
app.get('/show/:title', getShowByTitle)
Expected result is that sending a GET request using a show title as a parameter (String) returns a JSON response of just that show.
Any help or direction to some useful resources would be greatly appreciated. Thank you.
There are some issues here, first in SQL the name of the tables should be in plural "shows", second you are making the select without quotes, you need something like:
"SELECT * FROM show WHERE title = '$1'"
Third, since the user can use uppercase and down cases you need a more robust way to search for text using LIKE, ILIKE and ~, ~* operators.
https://www.2ndquadrant.com/en/blog/text-search-strategies-in-postgresql/
Fourth and more important, you are not filtering the string and you are at risk of suffering an SQL injection because "UPDATE admins SET password='newsom22th88';" is going to be executed in your database.
After some debugging my original code wasn't working because I had multiple verb-route matches. I solved the issue by creating a new unique verb-route match. Below is my complete code for querying using a String. Aarkerio's other points still hold; I need to alter my code to avoid SQL injection as well as create a more robust search.
const getShowByTitle = (request, response) => {
const title = request.params.title
pool.query('SELECT * FROM show WHERE title = $1', [title], (error, results) => {
if (error) {
throw error
}
response.status(200).json(results.rows)
})
}

using nodejs with pattern matching in CQL

const query= 'SELECT * FROM TEST WHERE "partitionId" = \'sr\' AND "name" LIKE \'%?%\'';
db.execute(query, ['B']).then(function(res) {
console.log(res);
}).catch(function(error) {
console.log(error);
});
I was not able to select data based on the pattern specified in the array.What is the exact way using CQL pattern matching with nodejs.I am getting "Invalid amount of bind variables" error.
NOTE: db has all the connection parameters
I think that you need to use following instead
const query= 'SELECT * FROM TEST WHERE "partitionId" = \'sr\' AND "name" LIKE ?';
db.execute(query, ['%B%']).then(function(res) {
...
P.S. Do you have corresponding indices built that support the LIKE expression? Cassandra doesn't work the same way as "standard" SQL databases.

Mongoose & MongoDB: Retrieve results narrowed by multiple parameters

I need to get data from MongoDB that is first narrowed by one initial category, say '{clothing : pants}' and then a subsequent search for pants of a specific size, using an array like sizes = ['s','lg','6', '12'].
I need to return all of the results where 'pants' matches those 'sizes'.
I've started a search with:
Product.find({$and:[{categories:req.body.category, size:{$in:req.body.sizes}}]},
function(err, products) {
if (err) { console.log(err); }
return res.send(products)
});
I really don't know where to go from there. I've been all over the Mongoose docs.
Some direction would be very helpful.
The mongoose queries can receive object like Mongodb would. So you can pass the search parameters separated by ,
Product.find({categories:req.body.category, size:{$in:['s','lg','6', '12']}})
For more information on $in, check here
For more information on $and operator, check here (note we can ommit the $and operator in some cases and that is what I did)

node.js mongodb projection ignored when there is a criterion

I am writing a node.js application using express, mongodb, and monk.
When I do a find with criteria only or with projections only, I get the expected result, but when I do a find with both, the full documents are returned, i.e., the projection is not performed. My code looks like this:
var collection = db.get('myDB');
collection.find({field1: "value"},{field2: 1, _id: 0},function(e,docs) {
...do stuff with docs...
});
It returns not just field2 but all fields of all the docs matching the criterion on field1. I can get field2 from this, but I don't like the inefficiency of it.
Is there a way to use both criteria and projections?
Monk uses a space-delimited string for field projection where you prefix a field name with - to exclude it.
So it should be:
var collection = db.get('myDB');
collection.find({field1: "value"}, 'field2 -_id', function(e,docs) {
...do stuff with docs...
});

Resources