0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【TypeORM】1件だけ取得したい時は find ではなく findOne / findOneBy を使う

0
Last updated at Posted at 2026-09-12

目的

TypeORMを用いて、複数データから一致する1件のデータ(オブジェクト)を取得する。

やろうとしたこと

一覧のレコードをクリックして詳細画面に遷移し、該当レコードのIDに一致する情報を取得・表示したい。
その際、find の中で where を用いてデータを取得しようとした。

引っかかったこと

find を使って条件に一致するデータを取得したところ、以下のような形式の「配列」で返ってきた。

[{ "id": 1, "title": "title1", "content": "content1" }]

該当データが1件のみであっても常に配列として返されるため、そのまま 〇〇.title のようにアクセスするとプロパティエラーになってしまった。
(〇〇[0].title として配列の先頭を取り出せば解決するが、コードが少し冗長になってしまう)

解決方法

配列ではなく単一オブジェクトを直接取得できる findOne や findOneBy を使うように修正した。
どちらを使ってもラップのない単一オブジェクトとしてデータを取得できる。

Before (find を使っていた実装)

const transaction = await transactionRepository.find({
    where: {
        id: id
    }
});

After (findOneBy または findOne に修正した実装)

// パターン1: findOneBy を使う(where を省略できてシンプル)
const transaction = await transactionRepository.findOneBy({
    id: id
});

// パターン2: findOne を使う(where を指定する)
const transaction = await transactionRepository.findOne({
    where: {
        id: id
    }
});

違いのまとめ

メソッド 返り値の型 主な用途・書き方の特徴 例
find() 配列 (Transaction[]) 複数件を取得する(常に配列で返る) [{ id: 4, amount: 1000 }]
findOne() 単一オブジェクト (Transaction | null) 1件取得(where などを指定する標準的な書き方) { id: 4, amount: 1000 }
findOneBy() 単一オブジェクト (Transaction | null) 1件取得(where を省略した簡略記法) { id: 4, amount: 1000 }
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?