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

200
Vistas
How to update data with duplicate values using Knex?

Let's say I have this array of data:

const ids = [
  '7d8206d2-74bc-4b90-a237-37f92486cde4',
  'e594fe7f-d529-4a2f-ab24-ffc4e102268c',
  '7d8206d2-74bc-4b90-a237-37f92486cde4'
]

As you can see, there are duplicates ids and when I want to update it like that:

        await knex("products")
            .increment("purchasesCount")
            .whereIn("id", ids) 

In my purchasesCount column I can see values (1, 1), but it should be (2, 1) because of duplicate ids. Is there a way to fix it?

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

The simplest solution is to issue one query per one purchase, as follows:

for (const id of ids) {
  await knex("products").increment("purchasesCount").where({ id: id });
}

If this is impossible for some reason (e.g. performance), then you have 2 options:

  1. Do in-memory bucketing and count how many of each ID you got. Then, do a bunch of increments with .whereIn("id", idsWithThisCountOnly). So, in the example above you'd do 2 updates, one for all ids which were found only once in the array and one for all ids which were doubled. You'll probably need a Map of id => count for counting duplicates, and will need to invert it later into the form of count => idsWithThisCountOnly[].
  2. Do not store counts in the database at all. Store only the IDs, duplicated, and use GROUP BY with COUNT when retrieving the data. This should offer better write performance (INSERTs are usually faster than UPDATEs), but at an increased storage size and slower reads.

Option 2. may be preferrable if you already have a "transactions" or "sales" table with line-items and are accessing the summary data infrequently.

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