I am using Node and Express with MSNODESQLV8 to write an API demo (my first) to get some rows from a remote SQL Server instance. My other get queries work fine when searching for an ID which is a number but I am unsure how to pass a value in the form of characters to a parameter in my query. Pretty sure req.params.id is not appropriate.
app.get("/productsname/:id", (req, res) => {
const productName = req.params.id;
const productsNameQuery = "SELECT * FROM Products WHERE ProductName = ?";
sql.query(connStr, productsNameQuery, [productName], (err, rows) => {
if (err) {
console.log(`Failed to get product by id ${req.params.id}. ${err}`);
res.sendStatus(500);
}else {
res.json(rows);
}
})
});
I want to take a product name (string?) in at the end of the url where it reads "id" and pass it as a value to the productName const. The end goal is to retrieve all rows from the SQL table where the product name is "processor" in the get url (http://localhost:2000/productname/proccesor). Perhaps I am passing the url incorrectly?
Apologies if this is really basic. I am very new to this.
Thanks in advance
Related
I am trying to count the number of documents in a table that satisfy a condition.
My code in node:-
const [washingCount, washedCount, dirtyCount] = await Promise.all([
pool.query("SELECT COUNT(*) FROM clothes WHERE status = 'washing'"),
pool.query("SELECT COUNT(*) FROM clothes WHERE status = 'washed'"),
pool.query("SELECT COUNT(*) FROM clothes WHERE status = 'dirty'")
])
But I am getting the error saying:
error: column "count" does not exist
And when I copy the same query over to PostgreSQL CLI, those output the desired results.
For full code refer:- https://github.com/js313/clothio/blob/master/index.js
Error stack trace:-
What am I missing here?
Thank you.
Why don't use group by?
select status, count(*) from clothes group by status
Edit
tested with a simple script like this and worked
require("dotenv").config({ path: "./.env" });
const Pool = require("pg").Pool;
const pool = new Pool({
user: process.env.DB_USER,
password: process.env.DB_PASSWORD,
host: process.env.DB_HOST,
port: process.env.DB_PORT,
database: process.env.DB_NAME,
});
async function main() {
const result1 = await pool.query("SELECT now()");
console.log(result1);
const result = await pool.query(
"SELECT status, COUNT(*) FROM clothes group by status"
);
console.log(result.rows);
}
main()
.then()
.catch((e) => console.error(e));
Edit 2
Found the issue in your repo code.
Route registration order matters, so you have this route.
app.get("/clothes/:cloth_id", async (req, res) => {
before the count one, so express is getting into this route and never reaching the count one.
To solve the issue move the /clothes/count route before the clothes/clothe_id one and that should solve the issue
I wasn't quite sure how to phrase this question so feel free to make corrections to improve it as desired.
My goal is to make an HTTP POST that will create comments for a post and add the comment to the database comments table. I believe this necessitates doing an INSERT as well as a JOIN to add the specific POST id to the comment.
This is my first time including two requests in one query so I am unsure if this is correct. I had read about using a UNION but haven't been able to figure out the correct syntax as none of the examples included quotes '' around their requests.
My post route:
router.post(`/posts/:id/comments`, (request, response, next) => {
const { id } = request.params; // tried with and without brackets {}
const { comment_body } = request.body;
// Testing for correct params
console.log(id);
console.log(comment_body);
pool.query(
'INSERT INTO comments(comment_body) VALUES($1)',
[post_id, comment_body],
'SELECT * FROM comments JOIN posts ON posts.post_id = commments.post_id',
(err, res) => {
if (err) return next(err);
}
);
});
What is strange is that this worked twice then stopped working. There are two entries in the comments table but any further posts don't do anything. This only worked from the comments form and not yet in Postman
This worked in two separate tests. When using brackets around the id, the post was created in the table but no post_id was joined on this table:
const { id } = request.params;
If I didn't use the brackets, the post_id was created in the data table:
const id = request.params;
Here are my tables:
CREATE TABLE posts(
post_id SERIAL,
user_id INT,
post_body CHARACTER varying(20000)
);
CREATE TABLE comments(
id SERIAL,
post_id INT,
user_id INT,
comment_body CHARACTER varying(20000)
);
Originally I had the post_id for comments set as serial but figured if that is supposed to be joined from the posts.post_id, it would probably need to be INT.
Thanks much for any direction.
I managed to solve this with the following:
router.post(`/posts/:id/comments`, async (request, response, next) => {
try {
const { id } = request.params;
const { comment_body } = request.body;
await pool.query
('INSERT INTO comments(post_id, comment_body) VALUES($1, $2)',
[id, comment_body]);
} catch(error) {
console.log(error.message)
}
});
Rather than using the JOIN, I just included the posts ID parameter in the original INSERT and imported it that way. I had initially thought I had to do it as a join but couldn't get a second SQL request to work. Thanks to snakecharmerb for the idea.
I also added async/await.
I am using sqlite database in Flutter. with provide and sqlite libraries. I want to get ordered list of String in the database when I get the list from sqlite. How can I achieve this? Thank you for your response!
You can use orderBy variable inside query method like this:
Future<List<SingleShiftModel>> getShiftModelsForParticularGroup(
String groupId) async {
Database db = await database;
final List<Map<String, dynamic>> maps = await db.query(
allShiftsTableName,
where: 'parentId = ?',
orderBy: "date ASC", // here you can add your custom order exactly like sqlite but EXCLUDE `ORDER BY`.
whereArgs: [groupId],
);
return List.generate(
maps.length,
(i) => SingleShiftModel.toShiftModelObject(maps[i]),
);
}
Team I'm trying to set the answer query in an answer into bot microsoft framework
This is what I do:
request = new Request(
"Here the string that returns me a number for example 763",
function(err, rowCount, rows)
{
console.log(rowCount + ' row(s) returned');
process.exit();
}
);
request.on('row', function(columns) {
columns.forEach(function(column) {
**session.send(column.value);
next();**
});
});
connection.execSql(request);
The consult is ok, but I get the error :
cannot create property 'type' on number
For me Session.send is the way to send a message to the user from bot framewok emulator.
Error - in Sql query syntax erorr:
"SELECT Medicina.Nombre FROM Medicina where='Aspirina'"
Change column name below query:
"SELECT Medicina.Nombre FROM Medicina where column_name='Aspirina'"
I'm writing a backup job, and need to fetch all classes in Parse-server, so I can then query all rows and export them.
How do I fetch all classes?
Thanks
Query the schemas collection.
GET /parse/schemas
Probably need to use the masterkey on the query. Not sure what language you're writing your job in but should be simple for you to create a REST query or create a node.js script and use the javascript/node api
--Added after comment below --
var Parse = require('parse/node').Parse;
Parse.serverURL = "http://localhost:23740/parse";
Parse.initialize('APP_ID', 'RESTKEY', 'MASTERKEY');
var Schema = Parse.Object.extend("_SCHEMA");
var query = new Parse.Query(Schema);
query.find({
success : (results) => {
console.log(JSON.stringify(results));
},
error : (err) => {
console.log("err : " + JSON.stringify(err));
}});