I have this code that gets a single book from the TypeORM repository and it works fine.
public async getBook(name: string) {
const book = this.bookRepository.findOne({
where: [{ name: name }],
});
return book;
}
However, I want to implement some sort of GetManyBooks where I take in a list of names as strings use the find keyword instead of findone and return it. I thought it would be similar, but I'm having trouble finding any documentation online about this.
public async getManyBooks(name: string[]) {
const book = this.bookRepository.find({
where: [{ name: name }],
});
return book;
}
Is there a better way I should be tackling this problem?
CodePudding user response:
You can use the in
operator proivided by typeorm. Here are the docs
Also I recommend you dont use async
since you dont use await
and instead just return the promise itself. This will give you a Promise<Book[]>
.
import { In } from "typeorm";
// docs example
const loadedPosts = await connection.getRepository(Post).find({
title: In(["About #2", "About #3"]),
});
// In your case
public getManyBooks(name: string[]) {
return this.bookRepository.find({
where: {name: In(name)},
});
}