Even though the variable in Express js is unaware of the item update, I am still receiving the updated object

router.get("/:ticketid", async (req, res) => {
    try {
        const ticket = await ticketTable.findByPk(req.params.ticketid);

        const severityTimeSpaninMinutes = {
            "Severity 1 - Critical Business Impact": 1 * 60 * 24,
            "Severity 2 - Significant Business Impact": 3 * 60 * 24,
            "Severity 3 - Some Business Impact": 90 * 60 * 24,
            "Severity 4 - Minimal Business Impact": 91 * 60 * 24
        }

        if (ticket) {
            //  check if time until caseSubmittedDate is more than 1 day
            const timeUntilCaseSubmittedDate = dayjs(ticket.caseSubmittedDate).diff(dayjs(), 'minute')
            //  if yes, then update the ticketSLA to "Not Met"
            if (timeUntilCaseSubmittedDate < -severityTimeSpaninMinutes[ticket.priority]) {
                await ticketTable.update({
                    ticketSLA: "Not Met"
                }, {
                    where: {
                        tID: ticket.tID
                    }
                })
            }
            // get attachments based on R_TID
            const attachments = await attachmentTable.findAll({
                where: {
                    R_ID: ticket.tID,
                    columnName: "Requestor"
                }
            })

            res.json({
                data: { ...ticket.toJSON(), attachments },
                statusCode: 200,
                statusMessage: `Successfully fetched ${ticket.toJSON().ticketNo}`
            })
        } else {
            res.status(400).json({
                statusCode: 400,
                statusMessage: "Missing Ticket"
            })
        }
    } catch (err) {
        return res.status(500).json({
            statusCode: 500,
            statusMessage: err.message
        })
    }
})

Within this ticket variable is used to hold a specific item retrieved from the ticket table initially through sequelize

Furthermore, an update operation occurs within a conditional statement on the table.

Interestingly, in the line

data: { ...ticket.toJSON(), attachments },
the ticket object automatically reflects the updated value from the table, even though it was declared prior to the update.

I am curious about the intricate workings of this process. How does this mechanism operate in detail?

Answer №1

When dealing with variables, it can sometimes seem like they are being assigned by reference rather than by value. Many programming languages automatically assign objects by reference, which can be thought of as a shortcut or pointer to the original object. On the other hand, primitives are typically assigned by value, which may feel more familiar to you. If you want to assign an object by value, you will need to make a copy of that object.

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

Can the console logs be disabled in "Fast Refresh" in NextJS?

When I'm running multiple tests, my browser's console gets cluttered with messages every time a file is saved. Is there a way to disable this feature? For example: [Fast Refresh] completed in 93ms hot-dev-client.js?1600:159 [Fast Refresh] rebuil ...

Implementing a constant loop repeatedly in NextJs

I am seeking assistance with printing the <Icon /> 700 times on a single page. As a newcomer to NextJs, I have successfully used a for loop to console.log the icons but am unsure of how to actually display them. Any help would be greatly appreciated. ...

When utilizing a Javascript event listener within ReactJS with NextJS, the dynamically imported module without server-side rendering fails to load

Hello everyone, I am new to ReactJS and NextJS and would really appreciate some advice on the issue below. Thank you in advance! Here is my current tech stack: Node v16.6.1 React v17.0.2 Next.js v10.0.4 I'm working on implementing a carousel and si ...

What is the best way to trigger the opening of a Component upon an onPress event?

One challenge I am facing is implementing a button in my app's Screen that should open a self-made Modal component on the same screen. To achieve this, I have set up a visible state in the screen and created an onPress handler for the button to toggl ...

Enhancing security by utilizing encrypted cookies and a session store to protect requests

Recently, I discovered that the application I have been consulting on is using unencrypted cookies. The front end (Angular) regularly uses the following code to extract the user id: var user_id = JSON.parse($cookies.userdata).id; I am concerned that a ma ...

Share a Node.js Express.js npm package for universal access within the project

Here is my current folder structure. /app.js /src /routes /controllers Within the routes folder, there are multiple javascript files that all require the passport.js package like so: const passport = require('passport'); Is it possible to c ...

When implementing jQuery AJAX, remember to properly encode script tags to prevent any

Looking for a way to avoid script tags in content loaded through AJAX? Check out this approach: $.ajax({ cache: false, type: 'GET', url: 'index.html', success: function(response) { $(response).find('<sc ...

Trigger Polymer() callback when the element is displayed

Is there a way to implement a callback in the Polymer({}) object that triggers every time the element is displayed? ready doesn't fit the criteria as it's called during the initial page load when the element is created. I'm looking for an ...

one webpage featuring HTML-based charts - visual data representation in HTML

I am looking to create HTML charts using a single file that includes JavaScript and jQuery. Specifically, I need the ability to generate line charts, pie charts, and other types of graphs, all within one file. I do not have much knowledge about JavaScript ...

CodeMirror version 5.62.3 is experiencing some challenges with the scrollbar functionality, editor size, and line wrapping

During my HTML/CSS/JS coding session, I encountered a challenge with CodeMirror version 5.62.3. Specifically, I was striving to make the scrollbar visible in the code editor, using C# as the language mode. However, despite setting the editor's height ...

Adapting the colors of various elements throughout the entire webpage

My goal is to incorporate color-switch buttons on my webpage. When these buttons are clicked, I want the existing colors to change to different shades. However, my challenge lies in the fact that these colors are used for various elements such as backgro ...

Tips for incorporating a variable into a JSON object value when dynamically constructing an object

Is there a way to dynamically create an array of objects using a for loop? I have different arrays with values for the key value pairs of these objects. The code snippet I tried is not producing the expected result. var characters = ['Iron Man', ...

Is it feasible to activate an action on a click of a Vimeo video?

Is there a way to activate an event by clicking if a video is set with background=1 and has no controls? This particular video is from Vimeo, using a plus account which allows for setting background=1. The scenario involves a Vimeo video playing on loop ...

Using React Higher Order Components with several different components

Is it possible to create a React HOC that can accept two components instead of just one wrapped component and toggle between them? For instance, in the code snippet below, rather than having <h3>component one</h3> and <h3>component two< ...

The visibility of the button is not functioning properly on iOS within the Kony platform

Currently, I am involved in a project using Kony and have encountered an issue where I need to hide a button based on a certain condition. I have implemented the code provided below, which functions correctly on Android devices but not on iOS. I have gone ...

Guide on organizing a series of links into an array

I'm looking to create a series of links: Using a for loop to generate these links, I want to store every x-th value into the photos[i] array. The code I have so far is not working as expected due to issues with string concatenation. My knowledge of J ...

Passing parent form controls from an Angular 4 FormGroup to a child component

I have implemented Angular Reactive Forms FormGroup and FormArray in my project. The issue I am facing is related to splitting my form fields into child components and passing the parent form controls to them. I expected this to be a straightforward proces ...

Can a Node.js server be configured with Nginx as a reverse proxy?

I am facing a challenge with my Express server running an Angular app. Following a tutorial by this individual , I have successfully set up my app at my Digital Ocean IP address + port 8000, ensured it runs continuously with an upstart service, and install ...

Merge two separate mongodb records

Just getting started with javascript / express / mongodb. For my initial project, I am working on a simple task manager where todos are categorized by priority - "high," "mid," or "low." However, I am facing an issue when trying to display different entri ...

Typescript and the way it handles responses from REST APIs

Starting off, I must mention that I am relatively new to TypeScript, although I have been a JavaScript developer for quite some time. I am in the process of transitioning my existing JavaScript application to TypeScript. In the current JavaScript app, the ...