Issue with TypeORM @BeforeInsert causing a field in Entity not to be populated with value

Currently, I am facing an issue where I am attempting to update or insert into a token field before the record is saved. However, when utilizing the @BeforeInsert hook, I encounter the following error:

"error": "Cannot read property 'concat' of undefined"
. I grasp the error message, but it is perplexing why it is occurring since this.tokens is a property of the entity user class.

@Entity('users')
class User extends BaseEntity {
@Column({
    type: 'jsonb',
    array: false,
    default: () => "'[]'",
    nullable: false,
  })
  tokens!: Array<{ token: string }>;
}

@BeforeInsert()
  toJSON(): object {
    const user = this;
    user.tokens = user.tokens.concat({ token: "34e5trfkljhkhgufy42343567" });
    // user.save();
    user.resetlink = "https://www.google.com";
    console.log('second', user)
    return user;
  };

On the other hand, when I utilize the afterinsert hook, it functions as intended but the token ends up being assigned twice, which is not the desired outcome.

@AfterInsert()
  toJSON(): object {
    const user = this;
    user.tokens = user.tokens.concat({ token: "34e5trfkljhkhgufy42343567" });
    // user.save();
    user.resetlink = "https://www.google.com";
    console.log('second', user)
    return user;
  };

Answer №1

Within your column decorator, the entity is being given a default value of an empty list for the tokens field. However, when the BeforeInsert function is invoked, this default value has not yet been assigned, resulting in tokens being undefined and leading to the error.

It is unclear why the value is being assigned twice in the AfterInsert function, but it is possible that this.save() is being called, triggering another execution of AfterInsert.

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

How can you update an image's source when hovering over it?

My goal is to switch the image source upon mouseover using a combination of asp.net and javascript. Here is the code I am currently using: <asp:ImageButton id="button" runat="server" Height="65px" ImageUrl="~/images/logo.png" OnMouseOver="src='~ ...

Unbinding or undoing an 'onclick' event when another 'onclick' event is triggered

I am facing an issue where clicking on elements with 'onclick' functions works as expected, but when I click on a different element with another 'onclick' function, the first one remains active. What I actually want is for the previous ...

Add a new value to an object and ensure that only the unique value is appended to the first

I have a scenario where I have 2 objects, and I need to add a new key value pair to only the first matching object of its kind. Obj1 [{ buyDate: "yesterday", productId: "0001", consumerId: "John", price: 10 // add new key valu ...

Tips on including variables within quotation marks in JavaScript

I'm currently working on a JavaScript project using Pug. My goal is to use Express and MongoDB to develop a CRUD application that generates an edit button for each post, triggering a specific event when clicked. However, instead of the desired resul ...

Determine the total quantity of colored cells within a row of an HTML table and display the count in its own

I need assistance with a table that has 32 columns. From columns 1 to 31, I am able to fill in colors by clicking on the cells. However, I now want to calculate and display the number of cells that are not colored in the last column. This task must be co ...

What is the best way to send data to PHP while moving objects between different div elements?

I have a situation where I have two parent divs containing dynamic children divs, and I want to enable POST requests to PHP when items are dragged from one side to the other (and vice versa). Here is the Javascript code I am using: function allowDrop( ...

Determine the frequency of each element in an array and arrange them in ascending order

In my quest to locate occurrences of numbers within an array, I aimed to display the numbers and their respective frequencies in ascending order. Here is what I was trying to achieve: let arr = [9,-10,2,9,6,1,2,10,-8,-10,2,9,6,1]; // {'-10': 2, ...

Is it considered poor form to use res.locals in Node.js with Express?

Is it considered bad practice to use res.locals as shown in this code example? Are there potential issues that could arise from using it in this manner? app.use((req, res, next) => { const session = req.cookies.session if (session) { db. ...

I am looking to implement the ajax data variable for use in a submit button. How should

I'm facing an issue where, upon clicking the submit button, I am unable to receive the value yearend. Instead, I am getting an undefined value. How can I ensure that I receive the correct yearend value when I click the submit button? Here is my code: ...

Troubleshooting: Why is my express-fileupload failing to upload images

I'm currently working on implementing a feature that allows users to upload a profile image for their profiles. I have the form set up the way I want it, but I keep encountering an error that says TypeError: Cannot read property 'profilePicUpload ...

Combining for loops and async waterfall for optimal efficiency

Hey there, I'm just starting out with Nodejs and could really use some advice on writing more efficient code. Let me explain my issue. So, I have this function that is utilizing an async waterfall model. My goal is to call this function within a loop ...

Choose checkboxes based on the checkboxes that were previously selected

My goal is to have a checkbox automatically selected based on the previously selected checkbox. For example, if I select the first checkbox (which has a specific class), then only the checkbox with the same class as the first one should be selected using j ...

Using the && operator for conditional rendering in a React return statement

How should I format my return statement in a class component when using the && operator in the condition like this: if (x === null && y === null) If the condition is met, display this HTML: <div className="col-12"> <SomeComponent /> < ...

Problem with selecting dates in rangepicker

Having trouble with my recursion code for selecting dates in a rangepicker: recurse( () => cy.get('.mantine-DatePicker-yearsListCell').invoke('text'), (n) => { if (!n.includes(year)) { //if year not f ...

The compatibility between Polymer JS and Rails Turbolinks is problematic

Currently, I am facing a challenge in integrating PolymerJs with a Ruby on Rails project that has Turbolinks enabled. The issue arises when I click on a link - the new page loads correctly but my Polymer components do not reinitialize. They appear as if no ...

The Axios and TypeScript promise rejection error is displaying an unknown type- cannot identify

Currently, I am encountering an issue where I am unable to utilize a returned error from a promise rejection due to its lack of typability with Typescript. For instance, in the scenario where a signup request fails because the username is already taken, I ...

Issue with React component not reflecting updated state following Axios call

I have a series of chained axios calls to different APIs. When I log the state inside the function, I see that it is being updated correctly. However, when I log the state in the render() method, I do not see the updated state. The function is triggered a ...

Enhancing a React modal to enable user input for updating state variables

Is there a way to utilize user input from the page to dynamically create elements in a React.js application? In my app.js file, I have defined some constants at the beginning for mock data: const book1 = [ {id: uuid(), content: 'reflections&apos ...

What is the best way to dynamically add the 'required' attribute to an input field?

My responsibility was to dynamically add required fields to all elements on each state that the user selected as required. In my database, I have a table containing the input ID (each input has a unique ID) and a boolean field indicating whether or not a r ...

Issue with Electron | JavaScript Runtime

Attempting to utilize WebTorrent with Electron and Node.js for torrent downloading. Here is the code snippet in main.js: const electron = require('electron') const { app, BrowserWindow } = electron const path = require('path') const u ...