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.
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.
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!