NestJS - How to properly update with TypeOrm

Viewed 22822

I have this controller:

async reinstate(@Param() getSubscriptionDto: GetSubscriptionDto) {
        const reinstatedSubscription = await this.subscriptionsService.reinstateById(
            getSubscriptionDto.id
        )
        if (reinstatedSubscription.affected === 0) {
            throw new NotFoundException('Subscription not found')
        }

        return 204
    }

And the service:

const subscription = {
            id: subscriptionId,
            status: 'pass',
            cancelledAt: null,
        }

        return await this.subscriptionRepository.update(
            subscriptionId,
            subscription
        )

The update always returns object, which has "affected" property. As I have seen, if it makes an update value of affected is 1, and if I send non existing subscription, affected is 0.

Thus in my controller I have this:

 if (reinstatedSubscription.affected === 0) {
                throw new NotFoundException('Subscription not found')
            }

It does work, but is this the only way of doing it? And additionally, how can I return no content response?

1 Answers

There are multiple ways to update record in typeorm:

  1. use Query Builder
import {getConnection} from "typeorm";

await getConnection()
    .createQueryBuilder()
    .update(User)
    .set({ firstName: "Timber", lastName: "Saw" })
    .where("id = :id", { id: 1 })
    .execute();

  1. use save

Saves a given entity or array of entities. If the entity already exist in the database, it is updated. If the entity does not exist in the database, it is inserted. It saves all given entities in a single transaction (in the case of entity, manager is not transactional). Also supports partial updating since all undefined properties are skipped. Returns the saved entity/entities.

import { getMongoRepository } from 'typeorm';

repo = getMongoRepository(User);
await repository.save(user);
  1. use update as you mentioned

Specially, there are updateOne and findOneAndUpdate, updateMany api in MongoRepository API.For more detail you can referenced here

Related