4

I'm new to using Node.js and PostgreSQL.

I'm creating a post request with insert query.
How can I return inserted values to browser at the same time?

app.post('/car_create', (req, res) => {
    const make = req.body.create_make;
    const model = req.body.create_model;

        client.query(`INSERT INTO cars (make, model) VALUES ($1, $2)`, [make, model], (error, results) => {
            if (error) {
                throw error
            }
            res.status(201).send(`Car added with ID: ${results};`);
            console.log(res);
            res.end();
        });
}); 

How I can retrieve the data from response ?
Do I need to modify this line somehow?

            res.status(201).send(`Car added with ID: ${results};`);       

1 Answer 1

6

First you need return the values after you insert them in PostgreSQL. To do so, add a RETURNING clause to your query, like so: INSERT INTO cars (make, model) VALUES ($1, $2) RETURNING id, make, model. Add more columns in the RETURNING clause if you have and want more.

Then in the callback, the results variable should contain information about your query, including what it returned (in the rows key). You can send it to the client in many ways, but to return it in a similar way as you currently do , you could do this:

const {id, make, model} = result.rows[0]; // rows is an array of rows returned, and since we do a single INSERT we only have one row, with the returned columns from the query
res.status(201).send(`Car added with ID ${id}, make "${make}" and model "${model}".`);

If you want to use this data on the frontend it would be easier and more convenient to possibly send the data as JSON, like so: res.status(201).send(results.rows[0]);

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

3 Comments

When i add RETURNING id, make, model i have an ERROR.
What is the error? I assumed you have a column called id but you could try without it?
Thanks for your answer Samuel!

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.