Search code examples
nestjstypeorm

TypeORM - Update only values that are provided and leave the rest as they are


How would I approach this using TypeORM?

I have an Entity lets call it EntityA.

I have 1 EntityA in my database with name = Joe, age = 17

Now my front end sends a post request to my API with an Object like { name: Joe, age: 16 }

How can I tell type orm to update the EntityA in the database with the name of "Joe" and only update the provided values that differ from what is currently stored in the database (age in this case) ?


Solution

  • I've had the same issue, especially with undefined values in nullable columns. Take my project's Product repository update function as a starting point. I've used conditional spread syntax (...) to "build" the query dynamically. See this for more information.

    async function update(id: string, user: User): Promise<User> {
        // Update
        await userRepository.update(id, {
          ...(user.name && { name: user.name }),
          ...(user.surname && { surname: user.surname }),
          ...(user.age && { age: user.age }),
        });
    
        // Return
        return this.repository.findOneOrFail(id);
      }
    

    Update only the columns that are present in user. E.g: If no user.name is present does not update it since it's not in the update object.