"Bulk" Updating with Postgres DB and JS/Knex/Express Question

Viewed 21

I have an update endpoint that when an incoming (request) contains a site name that matches any site name in my job site's table, I change all those particular DB entries status to "Pending Transfer" and essentially clear their site location data.

I've been able to make this work with the following:

async function bulkUpdate(req, res){
  const site = req.body.data;
  const data = await knex('assets')
  .whereRaw(`location ->> 'site' = '${site.physical_site_name}'`)
  .update({ 
    status: "Pending Transfer",
    location: { 
      site: site.physical_site_name, 
      site_loc: { first_octet: site.first_octet, mdc: '', shelf: '', unit: ''} //remove IP address
    },
    //history: ''

  }) //todo: update history as well
  .returning('*')
  .then((results) => results[0]);
  res.status(200).json({ data });
}

I also want to update history (any action we ever take on an object like a job site is stored in a JSON object, basically used as an array.

As you can see, history is commented out, but as this function essentially "sweeps" over all job sites that match the criteria and makes the change, I would also like to "push" an entry onto the existing history column here as well. I've done this in other situations where I destructure the existing history data, and add the new entry, etc. But as we are "sweeping" over the data, I'm wondering if there is a way to just push this data onto that array without having to pull each individual's history data via destructuring?

The shape of an entry in history column is like so:

[{"action_date":"\"2022-09-06T22:41:10.232Z\"","action_taken":"Bulk Upload","action_by":"Davi","action_by_id":120,"action_comment":"Initial Upload","action_key":"PRtW2o3OoosRK9oiUUMnByM4V"}]

So ideally I would like to "push" a new object onto this array without having (or overwriting) the previous data.

I'm newer at this, so thank you for all the help.

1 Answers

I had to convert the column from json to jsonb type, but this did the trick (with the concat operator)...

    history: knex.raw(`history || ?::jsonb`, JSON.stringify({ newObj: newObjData }))
Related