如何使用 TypeORM 存储 JSON 对象
如果你想用 TypeORM 存储某种灵活的数据,你可以将它们保存为 JSON。您可以将列类型指定为simple-json。这可以帮助您轻松存储和加载 Javascript 对象。
为了更清楚,让我们检查一个具体的例子。
1. 定义一个名为Product的实体:
// Product entity
import {
Entity,
PrimaryGeneratedColumn,
Column,
CreateDateColumn,
} from 'typeorm';
@Entity({name: 'products'})
export class Product {
@PrimaryGeneratedColumn()
id: number;
@Column()
name: string;
// Column with JSON data type
@Column('simple-json', {nullable: true})
otherInfo: {
description: string;
freeShipping: boolean;
weight: number;
color: string;
};
@Column({default: 0})
price: number
}
- 向数据库添加新产品:
const productRepository = dataSource.getRepository(Product);
const product = new Product();
product.name = 'KindaCode.com';
// JSON stuff here
product.otherInfo = {
description: 'This is a description',
freeShipping: true,
weight: 1,
color: 'red',
};
product.price = 100;
await productRepository.save(product);
在您的数据库中查看您的表格产品时,您会看到这一点(将注意力放在otherInfo列上):
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布,任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站。本站所有源码与软件均为原作者提供,仅供学习和研究使用。如您对本站的相关版权有任何异议,或者认为侵犯了您的合法权益,请及时通知我们处理。