GraphQL: Field not defined on type
GraphQLで存在しないフィールドをクエリした際のエラー原因と解決策
概要
GraphQLスキーマに定義されていないフィールドをクエリした際に発生するエラーです。
エラーメッセージ
```json { “errors”: [ { “message”: “Cannot query field "email" on type "User".”, “locations”: [{ “line”: 3, “column”: 5 }] } ] } ```
原因
- フィールド名のタイプミス: スペルミス
- スキーマとの不一致: クライアントが古いスキーマを参照
- 型の間違い: 別の型のフィールドを指定
- 権限による非公開: 認証状態でスキーマが異なる
解決策
1. スキーマを確認
```graphql
スキーマ定義
type User { id: ID! name: String! emailAddress: String! # email ではなく emailAddress }
正しいクエリ
query { user(id: “1”) { id name emailAddress } } ```
2. Introspectionでスキーマを取得
```graphql query { __type(name: “User”) { fields { name type { name } } } } ```
3. フラグメントで型を明示
```graphql query { search(query: “test”) { … on User { name emailAddress } … on Post { title content } } } ```
4. クライアントのキャッシュをクリア
```javascript // Apollo Client client.clearStore();
// または完全リセット client.resetStore(); ```
5. コード生成を再実行
```bash
GraphQL Code Generator
npx graphql-codegen
Apollo Codegen
npx apollo client:codegen ```
よくある間違い
- キャメルケース vs スネークケースの混同
- nullable と non-null の違い
- 古いスキーマのキャッシュ
関連エラー
関連エラー
GraphQL の他のエラー
この記事は役に立ちましたか?