Skip to content
Advertisement

Encountering a problem when trying to insert JSON data into my postgres database – Node.js

I’m having a problem when i try to save my JSON data into a database. Right now, i have this code here:

My service that retrieves and cache data from an API with the given parameter cep:

JavaScript

My route using the service:

JavaScript

It works with out problems: enter image description here

Here that comes the problem. When i try to insert the data into my database implementing this code into my service:

JavaScript

It doesn’t insert anything! And i tried to put only city instead of public.city and it still doesn’t work.

Here is my index.js file for the connection:

JavaScript

And my Database without any data: enter image description here

I created the table city directly from the dbeaver.

As you can see, my application is connected to the database: enter image description here

I’m a beginner and i would appreciate some help

Advertisement

Answer

You don’t seem to be using any library that handles dynamic mapping of your parameters to the required ordinal format into the query itself(like pg-parameterize) so the line:

const sql = 'INSERT INTO public.city(cep, logradouro, complemento, bairro, localidade, uf, ibge, gia, ddd, siafi) VALUES ?';

and more specifically the VALUES ? part shouldn’t be doing anything useful. Change that to:

const sql = 'INSERT INTO public.city(cep, logradouro, complemento, bairro, localidade, uf, ibge, gia, ddd, siafi) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10)';

as the pg npm package is using ordered parameters for parameterized queries.

Checkout the “Parameterized query” section in the docs for queries.

EDIT:

You’re either inserting the new record or getting an error. There is no other option. If you don’t see any new record in the db after refresh, then you’re just swallowing the error result in your code. As you’re going the async/await promise route, the code await pool.query(sql, values); will throw if something goes wrong.

Then, in your caller:

JavaScript

you catch the error. Check what the error object in the catch block is holding and you’ll see what’s wrong.

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement