How can I find all objects by ID?

Viewed 41

I got a list of ids and I would like to find in database the corresponding object.

I'm using Nodejs, Typescript, TypeORM and Postgres as database. My ids are UUID.


    async findAllByID(id: string[]): Promise<Entity[]> {
        const found = await this.model.find({ where: { id } });

        return found;
    }


It isn't working since I pass a list of string when only a string is expected. What's the solution please ?

2 Answers

A good way to figure this out is to first think how you would do it using SQL - assuming you have some experience with it. The query would look like

SELECT * FROM my_table WHERE id IN ('abc', 'xyz', '123')

Notice the IN keyword. Does Typeorm have something like that? Luckily it does! You can find it in the advanced section along with other options. Unfortunately it's not indexed well so you often have to scroll through the docs to find what you're looking for but there are plenty of examples in the typeorm docs for various operations.

To answer your question, the code will look something like

import { In } from "typeorm"
...
...
async findAllByID(ids: string[]): Promise<Entity[]> {
    const results = await this.model.findBy({ id: In(ids) });
    return results;
}

Alternatively, I think this will work as well

const results = await this.model.find({ where: { id: In(ids) } });

Hope it helps

If you want to pass more than one id, you must use IN find operator, for example where: {id: In(uuids)}

Related