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
Related
I have a table that stores gifts :
export interface Gift {
id: number
type : string
claim_status: string
user_id?: number
}
When a user claims one or multiple gifts, i want to select randomly some gifts and update them with the user_id. I tried using the knex limitfunction but it doesn't work for updating.
export const claimGifts = async (
user : User,
numberToClaim: number,
trx: Knex.Transaction
) => {
const gifts = await db<Gift>('gift')
.where({claim_status : 'available'})
// limit the amount of updated to numberToClaim be slicing randomly
.update({user_id : user.id, claim_status : 'claimed'}, '*')
.transacting(trx)
return gifts
}
Any idea ?
You should first construct a SQL query, and then convert it to Knex usage.
I would use nested query for selecting random entries, something like:
Update gift set user_id = 'MY_USER_ID' Where id IN (Select inner_g.id from gifts as inner_g where claim_status='available' Order by RAND() Limit 3)
When it converted to Knex, it looks like:
const gifts = await db<Gift>('gift')
.update({
user_id: user.id,
claim_status: 'claimed',
})
.whereIn(
'id',
db('gift as inner_g')
.columns('inner_g.id')
.where({ claim_status: 'available' })
.orderBy(db.raw('RAND()') as any)
.limit(3)
);
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 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
I am facing a problem with route parameter error catching. Here is the situation explained below.
The route params are as follows for displaying data in components of navbar:
http://localhost:4200/{ company_type }/{ company_name }/{ org-id }/{ component_name }
The website is opening even when I change the company_name to any string and company_id to null || 14cd156. I will get articles when I change company name in route. But, when I change id I get an error
core.js:1624 ERROR Error: Uncaught (in promise): HttpErrorResponse: {"headers":{"normalizedNames":{},"lazyUpdate":null},"status":404,"statusText":"Not Found","url" ...
The API doesn't check for company name. It only checks the company id company coming from route params. What I want to do is: to navigate to not-found page in case the company_name and company_id are invalid. Let's say,
company_type = consulting
company_name = ABC
id = 1
page=Article
In page Article when I change http://localhost:4200/consulting/ABC/5/articles to http://localhost:4200/consulting/3edsads/5/artciles the website shows data of Articles page. But, the data is route parameter is wrong.
articles.component.ts
getOrgArticles(page: number = 1) {
let queryParams = this.getQueryParams(page);
this.queryArticles =
this.service.getOrgArticles(queryParams).
subscribe((data: any) => {
this.page = page;
this.pageSize = queryParams['per-page'] || this.pageSize;
this.articles = this.articles.concat(data['articles']);
this.pageCount = data._meta.pageCount;
this.isLastPage() ? this.hideNextButton() : this.showNextButton();
this.totalCount = data._meta.totalCount;
},
error => {
});
}
service.ts
getOrgArticles(queryParams) {
const qpString = this.queryString(queryParams);
return this.http.get(`${this.api}/articles?${qpString}`);
}
I really wish to find some solution from you. Thank you
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));
}});