How can I add data to a relational table that includes a foreign key reference?

There are two tables that are related with a one to many relationship:

envelopes:

CREATE TABLE envelopes (
    id integer DEFAULT nextval('envelope_id_seq'::regclass) PRIMARY KEY,
    title text NOT NULL,
    budget integer NOT NULL
);

transaction:

CREATE TABLE transactions (
    id integer DEFAULT nextval('transaction_id_seq'::regclass) PRIMARY KEY,
    envelope_id integer REFERENCES envelopes(id),
    date date NOT NULL,
    title text NOT NULL,
    amount integer NOT NULL
);

Each transaction is linked to an envelope and also affects the budget of the envelope.

I'm trying to find the best way to execute this query in Express.js but facing some difficulties.

This is what I have for POST request on /envelopes/:id/transactions:

...
        const sql = "INSERT INTO transactions(title, amount, date, envelope_id)VALUES($1, $2, $3, $4) RETURNING *";

  try {
    const newTransaction = await db.query(sql, [title, amount, date, id]);
    res.status(201).send(newTransaction.rows[0]);
  } catch (err) {
    return res.status(500).send({
            error: err.message
        });
  }
...

I'm unsure if this is the correct approach. Any suggestions?

Answer №1

Consider utilizing a Transaction to ensure the successful execution of all Queries or none at all.

BEGIN TRANSACTION

INSERT INTO transaction_history (name, price, timestamp, category_id) VALUES ($1, $2, $3, $4);

UPDATE budgets SET
    total = total - <Value to be Deducted>
    WHERE id = <budget ID>;

COMMIT TRANSACTION;

SELECT * FROM transaction_history ORDER BY timestamp DESC LIMIT 1;

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best way to include a line break in a Pug variable when returning it?

When I use express and pug to inject a text variable in my pug file, the return lines are not being recognized. Even though the string contains several \n characters. How can I replace the line returns with tags in pug? Here is how I inject the va ...

Seeking a JavaScript tool specialized in compressing POST data?

Currently working on a chrome extension that sends HTML strings to a server using POST requests. Interested in compressing these large strings before sending them. Wondering if there are any JavaScript libraries that can help with this? ...

Using AngularJS to filter an array using the $filter function

Looking for a more elegant way to achieve the following task: myList.forEach(function(element){ if (!['state1', 'state2'].contains(element.state)){ myFilteredList.push(element) } }) I was thinking of using $filter('fi ...

Sending handlebars variable to the client-side JavaScript file

I am currently working on an application using node.js along with express and handlebars, and I'm trying to find a way to transfer handlebars data from the server to client-side JavaScript files. Here is an example: //server.js var person = { na ...

Retrieve information about a parent's data related to child events in Vue.js

I'm working with two components nested inside each other. The parent component has a click event that needs to modify the data value of the child component. <template> <div> ..... ..... <my-component :op ...

When switching back to the parent window and attempting to execute an action, a JavaScript error is encountered

Currently automating a SnapDeal eCommerce website A challenge I am facing is an error message in the console: The issue occurs when transitioning from a child window back to the parent window and performing operations on the parent window. //Automa ...

Run the js.erb code only when a certain condition is met

I'm feeling a bit lost when it comes to CoffeeScript and JS. I have a quick editing feature that sends an AJAX request and updates the database. Currently, I manually change the edited content's place and display it, but it feels like a workaroun ...

"Encountered a problem during the installation of pm2 for Node.js

I am in the process of installing pm2 (https://github.com/Unitech/pm2) Encountered the following error while doing so: D:\_Work>npm install pm2 -g --unsafe-perm npm WARN `git config --get remote.origin.url` returned wrong result (http://ikt.pm ...

Interacting with Apexcharts: Exploring a Tiny Column with Hover

While using apexcharts, I encountered an issue with small columns. It can be quite challenging to render the tooltip properly because you have to hover very precisely over the column. Query: Is there a way to expand the hover area to make it easier to int ...

Utilizing Environment Variables Across Multiple Files in Node.js with the Help of the dotenv Package

I am currently developing a basic application that utilizes the Google Maps API and Darksky API. To keep my API keys secure, I have implemented dotenv for key management. I have successfully integrated dotenv in my main file (app.js), but now I need to a ...

Setting the locale manually in sailsjs via user input

Is there a way to manually switch the locale for a SailsJS application? I am thinking of adding a dropdown on the navigation bar where users can choose their preferred language for viewing the site. Mike ...

Changes made in Vuex will not be saved until they are manually committed using developer tools

One of the modules in my Vuex store is called login.js and it looks like this: import axios from "axios"; import router from "@/router"; axios.defaults.baseURL = process.env.VUE_APP_API_ENDPOINT; const state = { access_token: localStorage.getItem("acc ...

React automatic scrolling

I am currently working on implementing lazy loading for the product list. I have created a simulated asynchronous request to the server. Users should be able to update the page by scrolling even when all items have been displayed. The issue arises when ...

Changing the color of a Highcharts series bar according to its value

Playing around with Highcharts in this plunker has led me to wonder if it's possible to dynamically set the color of a bar based on its value. In my current setup, I have 5 bars that change values between 0 and 100 at intervals. I'd like the colo ...

What is the best way to send a variable to an event listener?

Forgive me if my issue seems insignificant to those well-versed in JS. I've developed an image carousel and am working on linking a thumbnail to a full-size image, so that when a user clicks on the thumbnail, the larger image appears in another sectio ...

The Java Selenium script encountered an illegal type error when trying to execute JavaScript through JavaScriptExecutor: driverFactory.CustomWebElement

I have a CustomWebDriver class that extends the functionality of JavascriptExecutor. Here is my implementation: @Override public Object executeScript(String script, Object... args) { return ((JavascriptExecutor) driver).executeScript(script, args); } ...

Python does not return the AJAX request back to JavaScript unless JQuery is not utilized

I have set up an XMLHTTPrequest in my javascript code to communicate with a flask location. Here's how I am doing it: var ourRequest = new XMLHttpRequest(); ourRequest.open("GET", "makeDiff") diff = ourRequest.send(); console.log(diff); Once the req ...

Establish a new <section> to serve as a distinct webpage

I have a question about creating multiple <section> elements on a page. I am looking to build an HTML document with several <section> tags, as outlined below. <html> <head> </head> <body> <sectio ...

Ways to verify the nodemon version that is currently installed on your local machine

On my Windows 10 machine, I recently installed nodemon locally in a project and now I'm curious to know which version is installed. Can someone please share the command to check the version of nodemon without needing to install it globally? My aim is ...

Developed technique for grouping arrays in JavaScript based on frequency of occurrence

I have a collection of arrays in javascript and I need to perform some calculations. Here is how my array looks: https://i.sstatic.net/m0tSw.png In each array: - The first value represents a code. - The second value indicates the size. - And the thir ...