【问题标题】:NestJS - How to properly update with TypeOrmNestJS - 如何使用 TypeOrm 正确更新
【发布时间】:2020-12-22 10:06:33
【问题描述】:

我有这个控制器:

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
    }

还有服务:

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

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

更新总是返回具有“影响”属性的对象。如我所见,如果它使受影响的更新值为 1,并且如果我发送不存在的订阅,则影响为 0。

因此在我的控制器中我有这个:

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

它确实有效,但这是唯一的方法吗? 另外,我怎样才能不返回任何内容响应?

【问题讨论】:

    标签: express nestjs typeorm


    【解决方案1】:

    在 typeorm 中有多种更新记录的方法:

    1. 使用Query Builder
    import {getConnection} from "typeorm";
    
    await getConnection()
        .createQueryBuilder()
        .update(User)
        .set({ firstName: "Timber", lastName: "Saw" })
        .where("id = :id", { id: 1 })
        .execute();
    
    
    1. 使用save

    保存给定的实体或实体数组。如果实体已存在于数据库中,则对其进行更新。如果实体在数据库中不存在,则将其插入。它将所有给定的实体保存在单个事务中(在实体的情况下,管理器不是事务性的)。还支持部分更新,因为所有未定义的属性都被跳过。返回保存的实体。

    import { getMongoRepository } from 'typeorm';
    
    repo = getMongoRepository(User);
    await repository.save(user);
    
    1. 如您所述使用update

    MongoRepository API 中有updateOnefindOneAndUpdateupdateMany api。更详细的可以参考here

    【讨论】:

      猜你喜欢
      • 2022-01-11
      • 2021-11-06
      • 2019-09-01
      • 2021-04-23
      • 1970-01-01
      • 2021-04-28
      • 2022-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多