Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

136
Views
Custom table query condition on node pg

Using pg https://www.npmjs.com/package/pg

I am planning on using a getUserBy(fields) function to fetch a single user, the parameter fields is an object that contains a single key (eg) {email:tst@tst.com}

My idea is to use this function with different types of fields (id,username,phone etc) instead of writing multiple functions I can keep it compact.

This is what my query looks like (I thought it was going to work) (db is the connection to pg)

db.query(`
    SELECT * FROM "Users"
    WHERE $1 = $2
`,[Object.keys(fields)[0],Object.values(fields)[0]])

Ideally this would be translated into

SELECT * FROM "Users"
WHERE email = tst@tst.com

But I dont know how I achieve this without using template literals. Is there away to make this possible?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

You cannot use a parameter for a column name. You'll need to build the part of the SQL with the identifiers dynamically:

const entries = Object.entries(fields);
const conditions = entries.map((e, i) => pgClient.escapeIdentifier(e[0])+' = $'+(i+1))
return pgClient.query(
  `SELECT *
  FROM "Users"
  WHERE ${conditions.join(' AND ') || 'true'}`,
  entries.map(e => e[1])
);
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!