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?

    1. 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.
    2. Cleaner code: Instead of coding several data manipulations, the effort is reduced as the code becomes straightforward.
    3. 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!

    The Query Force Team – Driving COE Initiatives | Oneclick IT Consultancy P Ltd
    About the Author

    The Query Force

    The Query Force is a dynamic and skilled team under Oneclick IT Consultancy P Ltd, committed to driving innovation and excellence through its Center of Excellence (COE) initiatives. With expertise spanning diverse technical domains, this team is dedicated to solving complex challenges, enhancing business performance, and fostering continuous growth. By leveraging cutting-edge technologies and best practices, The Query Force ensures that all COE initiatives are not only executed flawlessly but also bring measurable, long-term value to the organization and its clients.

    Share

    facebook
    LinkedIn
    Twitter
    Mail
    Database

    Related Center Of Excellence