NestJS - 如何使用 TypeOrm 正确更新

Ved*_*ic. 3 express typeorm nestjs

我有这个控制器:

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
    }
Run Code Online (Sandbox Code Playgroud)

和服务:

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

        return await this.subscriptionRepository.update(
            subscriptionId,
            subscription
        )
Run Code Online (Sandbox Code Playgroud)

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

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

 if (reinstatedSubscription.affected === 0) {
                throw new NotFoundException('Subscription not found')
            }
Run Code Online (Sandbox Code Playgroud)

它确实有效,但这是唯一的方法吗?另外,如何不返回内容响应?

spi*_* 王建 5

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

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

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

Run Code Online (Sandbox Code Playgroud)
  1. save

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

import { getMongoRepository } from 'typeorm';

repo = getMongoRepository(User);
await repository.save(user);
Run Code Online (Sandbox Code Playgroud)
  1. update按照你说的使用

特别是MongoRepository API 中有updateOneand findOneAndUpdate, updateManyapi. 更详细的可以参考这里