0

I have the following POSTGRESQL table

 id | name |    email     | weightsovertime |         joined          
 20 | Le   | [email protected] | []              | 2018-06-09 03:17:56.718

I would like to know how to push data (JSON object or just object) into the weightsovertime array.

And since I am making a back-end server, I would like to know the KnexJS query that does this.

I tried the following syntax but it does not work

update tableName set weightsovertime = array_append(weightsovertime,{"weight":55,"date":"2/3/96"}) where id = 20;

Thank you

1

2 Answers 2

1

For anyone who happens to land on this question, the solution using Knex.js is:

knex('table')
      .where('id', id)
      .update({
        arrayColumn: knex.raw(`arrayColumn || ?::jsonb`, JSON.stringify(arrayToAppend))
})

This will produce a query like:

update tableName 
  set weightsovertime = arrayColumn || $1::json
where id = 20;

Where $1 will be replaced by the value of JSON.stringfy(arrayToAppend). Note that this conversion is obligatory because of a limitation of the Postegre drive

Sign up to request clarification or add additional context in comments.

Comments

0

array_append is for native arrays - a JSON array inside a jsonb column is something different.

Assuming your weightsovertime is a jsonb (or json) you have to use the concatenation operator : ||

e.g:

update the_table
  set weitghtsovertime = weightsovertime||'[{"weight": 55, "date": "1996-03-02"}]'
where id = 20;

Online example: http://rextester.com/XBA24609

4 Comments

Thank you. Do you know how I would manipulate them in my server?
@user545871: what do you mean with "in my server"? That statement is run on the (Postgres) server.
I’m building a backend server that needs access to the database using tool such as knex.js
@user545871: I don't understand. Can't this knex things just run a SQL statement?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.