Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

138
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda