Database
How TypeORM Virtual Columns Improve Query Performance and Reduce Code Complexity
Overview
TypeORM is a widely used ORM for relational databases of applications built in Node.js. One such feature is virtual columns, which are features or fields that are not physically stored in the database, instead they are generated when a user requests for certain data.The database can also generate the column data on its own.
Why Use Virtual Columns?
- No need for extra calculations: The application does not have to account for these calculations as virtual columns supply the values directly from the database.
- Cleaner code: Instead of coding several data manipulations, the effort is reduced as the code becomes straightforward.
- Improved performance: Allowing the database to do the heavy computations means decreasing the quota for the application.
How to Implement Virtual Columns
The entity class allows you to set a virtual column by defining a getter function. This is a sample for the same:
@Entity()export class Product { @PrimaryGeneratedColumn() id: number; @Column() price: number; @Column() discount: number; // Virtual column for finalPrice get finalPrice(): number { return this.price - this.discount; }}
Accessing finalPrice is different in that it gets calculated every time the user also enters a price and a discount adding the two amounts together.
Example
Reducing extra manipulation of data
By following this way, You don’t have to manually calculate the discount:
async function getTotalValue() { const products = await productRepository.find(); const totalValue = products.reduce((sum, product) => sum + product.finalPrice, 0); console.log(`Total Value: ${totalValue}`);}
Ready to transform your business with our technology solutions? Contact Us Now!
Comment