Search code examples
sqlsavenestjstypeorm

how is UPDATE in Nestjs typeorm (pgsql) works?


In service.ts file

......
import { Repository } from "typeorm";
....
constructor(
    @InjectRepository(Profile)
    private readonly profileRepository: Repository<Profile>,
  )......

async updateprofile(profile_id:string, data: any): Promise<any> {
    try {
      console.log(profile_id);
      await this.profileRepository.update(data); //how to update without saving new row in db

      return {
        success: true,
        message: 'Successfully updated profile',
      };
    } catch (err) {}}....

i don't know how to update using particular id and body data without save.(This update syntax is wrong) because when save is used it make two rows which have unique values so error. and console.log(id) is giving output

{ profile_id: '29adb514-a10f-49c0-bde2-19dcbcf9e0b9' }

how to take value of that too?


Solution

  • Already profile_id is an object and not a string.

    Then, to modify the profile and not add a line in the DB, you just have to proceed as follows:

    import { Repository } from "typeorm";
    ....
    
    constructor(
        @InjectRepository(Profile)
        private readonly profileRepository: Repository<Profile>,
      ){}
    
    async updateprofile(dto: { profile_id: string }, data: any): Promise<any> {
        try {
          console.log(dto);
          await this.profileRepository.update(dto.profile_id, data); 
    
          return {
            success: true,
            message: 'Successfully updated profile',
          };
        } catch (err) {
          ...
        }
    }