【问题标题】:Search item in array at postgres using typeorm使用 typeorm 在 postgres 中搜索数组中的项目
【发布时间】:2020-11-04 08:41:00
【问题描述】:

数据库:postgres

ORM:Typeorm

框架:express.js

我有一个表,其中一个名为 projects 的字段是一个字符串数组。迁移中type设置为"varchar",de装饰器设置为"simple-array"

如果我收到查询 ?project=name_of_the_project 在我的 get 路线中,它应该尝试在简单数组中查找项目。

对于搜索,我的获取路线是这样的:

studentsRouter.get("/", async (request, response) => {
    const { project } = request.query;
    const studentRepository = getCustomRepository(StudentRepository);
    const students = project
        ? await studentRepository
                .createQueryBuilder("students")
                .where(":project = ANY (students.projects)", { project: project })
                .getMany()
        : await studentRepository.find();
    // const students = await studentRepository.find();
    return response.json(students);
}); 

问题是我收到一个错误,提示右侧应该是一个数组。

(node:38971) UnhandledPromiseRejectionWarning: QueryFailedError: op ANY/ALL (array) requires array on right side
    at new QueryFailedError (/Users/Wblech/Desktop/42_vaga/src/error/QueryFailedError.ts:9:9)
    at Query.callback (/Users/Wblech/Desktop/42_vaga/src/driver/postgres/PostgresQueryRunner.ts:178:30)
    at Query.handleError (/Users/Wblech/Desktop/42_vaga/node_modules/pg/lib/query.js:146:19)
    at Connection.connectedErrorMessageHandler (/Users/Wblech/Desktop/42_vaga/node_modules/pg/lib/client.js:233:17)
    at Connection.emit (events.js:200:13)
    at /Users/Wblech/Desktop/42_vaga/node_modules/pg/lib/connection.js:109:10
    at Parser.parse (/Users/Wblech/Desktop/42_vaga/node_modules/pg-protocol/src/parser.ts:102:9)
    at Socket.<anonymous> (/Users/Wblech/Desktop/42_vaga/node_modules/pg-protocol/src/index.ts:7:48)
    at Socket.emit (events.js:200:13)
    at addChunk (_stream_readable.js:294:12)
(node:38971) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)
(node:38971) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

它必须是该字段中的字符串数组,我不能使用foreignKey。

请在下面找到与此问题相关的我的迁移和模型:

迁移

import { MigrationInterface, QueryRunner, Table } from "typeorm";

export class CreateStudents1594744103410 implements MigrationInterface {
    public async up(queryRunner: QueryRunner): Promise<void> {
        await queryRunner.createTable(
            new Table({
                name: "students",
                columns: [
                    {
                        name: "id",
                        type: "uuid",
                        isPrimary: true,
                        generationStrategy: "uuid",
                        default: "uuid_generate_v4()",
                    },
                    {
                        name: "name",
                        type: "varchar",
                    },
                    {
                        name: "intra_id",
                        type: "varchar",
                        isUnique: true,
                    },
                    {
                        name: "projects",
                        type: "varchar",
                        isNullable: true,
                    },
                ],
            })
        );
    }

    public async down(queryRunner: QueryRunner): Promise<void> {
        await queryRunner.dropTable("students");
    }
}

型号

import { Entity, Column, PrimaryGeneratedColumn } from "typeorm";

@Entity("students")
class Student {
    @PrimaryGeneratedColumn("uuid")
    id: string;

    @Column()
    name: string;

    @Column()
    intra_id: string;

    @Column("simple-array")
    projects: string[];
}

export default Student;

编辑 - 01

在文档中我发现simple-array 存储用逗号分隔的字符串。我认为这意味着它是一个字符串,其中的单词用逗号分隔。在这种情况下,有没有办法在项目字段中找到哪一行有字符串?

链接 - https://gitee.com/mirrors/TypeORM/blob/master/docs/entities.md#column-types-for-postgres

编辑 02

外业项目存储了学生正在做的项目,所以数据库返回这个json:

  {
    "id": "e586d1d8-ec03-4d29-a823-375068de23aa",
    "name": "First Lastname",
    "intra_id": "flastname",
    "projects": [
      "42cursus_libft",
      "42cursus_get-next-line",
      "42cursus_ft-printf"
    ]
  },

【问题讨论】:

  • 看起来projects 列的数据类型应该是varchar[](或text[]),而不仅仅是varchar
  • @GMB ,我试过这个,我得到了同样的错误。
  • projects 中实际存储了什么?可以提供样品吗?
  • 可以直接查询数据库吗?您的 ORM 生成的内容没有帮助,因为它已格式化。您可以尝试一个功能:.where(":project = ANY ( string_to_array(students.projects, ','))", { project: project }) 您可能需要将分隔符调整为 ORM 使用的内容。
  • @MikeOrganek ,成功了!请给出答案,以便我检查。

标签: node.js postgresql typescript express typeorm


【解决方案1】:

根据 cmets 和对问题的更新,@WincentyBertoniLech 确定 ORM 将 projects 数组作为逗号分隔的文本值存储在 students.projects 列中。

我们可以使用string_to_array() 将其转换为正确的where 标准:

.where(":project = ANY ( string_to_array(students.projects, ','))", { project: project })

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-09-22
    • 2012-05-01
    • 2012-01-04
    • 1970-01-01
    • 2022-12-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多