NodeJS 用保存值更新唯一字段时typeorm更新失败

uqcuzwp8  于 2023-06-29  发布在  Node.js
关注(0)|答案(1)|浏览(123)

我在typeorm中有一个服务模型/表/实体,其中有一个名为service_name的字段,该字段是唯一的,当我尝试用相同的service_name值更新表时,它会抛出唯一约束违反错误,我不明白这一点,orm不应该忽略该更新吗?

@Entity('services')
class Service extends BaseEntity {
    @PrimaryGeneratedColumn('uuid')
    _id!: string;

    @Column({
        nullable: false,
        unique: true
    })
    service_name!: string;

    @Column({
        nullable: true
    })
    description!: string;
    

   

    async updateService(data: any) {
            try {
                const Manager = Service.getRepository().manager;
                return Manager.transaction(async transactionalEntityManager => {
                    const updates = Object.keys(data);
                    // const allowedupdates = [
                    //     'service_name',
                    //     'description',
                    //     'active'
                    // ];
                    const service = await transactionalEntityManager.findOneByOrFail(Service, { _id: data._id });
                    if (!service) {
                        throw new Error("Service not found");
                    }
                    // const isvalidoperation = updates.every((update) => {
                    //     return allowedupdates.includes(update as string);
                    // });
                    // if (!isvalidoperation) {
                    //     throw new Error({ error: "Invalid updates" } as unknown as string);
                    // }
                    updates.forEach((update) => {
                        service[update] = data[update];
                    });
                    await service.save();
                    //await Service.update({ _id: service._id }, data);
                    //await Service.insert(data);
                    // await transactionalEntityManager
                    //     .createQueryBuilder()
                    //     .insert(Service)
                    //     .set(data)
                    //     .where("_id = :_id", { _id: service._id })
                    //     .execute();
                    //.update(Service, { _id: service._id }, data);
                    //TODO update subservices if any and deactivate them
                    // const subservices = await Manager.find(Subservice, { where: { service: { _id: service._id } } })
                    // subservices.forEach(async (subserv) => {
                    //     subserv.active = false;
                    //     await transactionalEntityManager.save(subserv);
                    // });
                    //await transactionalEntityManager.save(service, );
                    return service;
                })
            } catch (error) {
                return new Error(error.message);
            }
        }
    
    }

也许我错了,我该怎么做呢?

ecfdbz9o

ecfdbz9o1#

在这种情况下抛出错误是一个完全正常的约定。只是做正确的错误处理。

相关问题