【问题标题】:How to use Query and where?如何使用查询以及在哪里?
【发布时间】:2021-09-01 22:24:18
【问题描述】:

我对查询和 Where 运算符有一些疑问。

所以实体是:

@Entity('clients')
@Index(['id', 'slug'], { unique: true })
export class Client extends BaseEntity {
    @ObjectIdColumn()
    id: ObjectID;

    @Column()
    slug: string;

    @Column()
    title: string;

    @CreateDateColumn({ type: 'timestamp', default: () => 'CURRENT_TIMESTAMP(6)' })
    createdAt: Date;

    @UpdateDateColumn({ type: 'timestamp', default: () => 'CURRENT_TIMESTAMP(6)', onUpdate: 'CURRENT_TIMESTAMP(6)' })
    updatedAt: Date;

    @Column({ default: false })
    isVisible: boolean;

    @OneToOne(() => PublicFile, { eager: true })
    @JoinColumn()
    logo?: PublicFile;
}

控制器方法:

@Get()
    async getClients(@Query() query): Promise<Client[]> {
        return await this.clientsRepository.find({
            select: ['id', 'slug', 'title', 'isVisible', 'createdAt', 'updatedAt'],
            where: { isVisible: query.visible ? Like('true') : Any([true, false]) },
            relations: ['logo'],
            order: {
                updatedAt: 'DESC'
            }
        });
    }

然后我尝试使用 url:/clients?visible=true 获取客户列表,然后我得到空数组

当我得到/clients 时,我也得到空数组

有没有正确的方法来使用查询以及在哪里?

【问题讨论】:

    标签: typescript mongodb nestjs typeorm


    【解决方案1】:

    这是我在项目中经常使用的解决方案。

    我使用条件 spread syntax (...) 动态地“构建”查询。请参阅this 了解更多信息。

    另外:

    1. 从查询中删除了select,因为它与* 相同。您有关系,为什么不也选择这些字段?
    2. 删除了await。据我所知,您希望返回 Client[] 的 Promise:find 方法已经返回了正确的类型。
    @Get()
    async getClients(@Query() query): Promise<Client[]> {
        return this.clientsRepository.find({
            where: {
                ...(query.visible !== undefined && { isVisible: query.visible }),
            },
            relations: ['logo'],
            order: {
                updatedAt: 'DESC'
            }
        });
    }
    
    

    【讨论】:

      猜你喜欢
      • 2021-11-29
      • 2012-12-06
      • 2020-08-30
      • 1970-01-01
      • 2013-01-29
      • 2016-09-24
      • 1970-01-01
      • 1970-01-01
      • 2023-04-02
      相关资源
      最近更新 更多