Home > Back-end >  How to save a nested object using typeorm and Nestjs?
How to save a nested object using typeorm and Nestjs?

Time:05-13

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.

CodePudding user response:

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));
  • Related