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

174
Views
What is the best way to perform multiple operations in a Knex transaction

I'm relatively new to knex and transactions. Basically I have to perform a bunch of batch inserts and updates across different POSTGRES tables and wanted to understand the best possible way to do it. Is the following a correct approach for this? I'm especially struggling with the batch-update part.

let fieldsToInsert = [{name:'Mike', age: 57, weight:66, gender:'M'}, ...]
let _user = {user_id:99, city:6}
return db.transaction(trx => {
            return trx.insert(fieldsToInsert)
            .into("users")
            .then(() => {
                const queries = fieldsToInsert.map((user) => {
                    db("biodata").update({"name": user.name}).where({"id": user.age})
                })
                return Promise.all(queries)
            }).then(() => {
                const queries = fieldsToInsert.map((user) => {
                    db("weight_and_gender".update({"weight": user.weight, "gender": user.gender}))
                })
                return Promise.all(queries)
            })   
        }).catch((err) => {
            console.log(err)
        })

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

0

await db.transaction(async trx => {
  const insertedRows = await trx('users').insert(fieldsToInsert).returning('*');
  for (let row in insertedRow) {
    await trx('biodata').update({name : row.name}).where('id', row.id);       
    await trx('weight_and_gender').update({weight : row.weight, gender: row.gender}).where('id', row.id);       
  }
});

Trying to run updates in parallel with Promise.all does not help anything. DB driver will buffer those anyways and run them sequentially in either way if they are executed in the same transaction.

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!