David
David

Reputation: 15

How to save a nested object using typeorm and Nestjs?

I have the following Data entity:

@PrimaryGeneratedColumn() 
id: number 

@Column() 
dataA: string 

@Column() 
dataB: string 

@Column() 
dataC: number

@Column() 
dataD: number

The data object I am trying to save:

const data = {
      dataA: "data 1",
      nestedData: {
        dataB: "data 2",
        dataC: 3
      },
      dataD: 4
      }

I then try to save it as follows:

await this.dataRepository.save(data)

I get an error that says something about dataB and dataC not being a part of Data entity even though it should be. Thanks.

Upvotes: 0

Views: 3630

Answers (2)

M C
M C

Reputation: 256

There is a 'json' type for the column type: https://typeorm.io/entities#column-types-for-mysql--mariadb

You can then write something like

@Column({ type: 'json' }) ressources: { title: string; ref: string }[];

Upvotes: 0

Pete Houston
Pete Houston

Reputation: 15089

You need to flatten it, write a function to do that before passing object into the Repository.

export function flattenData(data) {
    return {
        dataA: data.dataA,
        dataB: data.nestedData.dataB,
        dataC: data.nestedData.dataC,
        dataD: data.dataD,
    }
}

// then pass into Repository
await this.dataRepository.save(flattenData(data));

Upvotes: 3

Related Questions