You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Express GraphQL报错:Schema含重复命名类型‘String’求助

问题排查:GraphQL重复定义"String"类型错误

问题场景

开发Pinterest克隆项目时,启动服务触发以下报错:

Error: Schema must contain uniquely named types but contains multiple types named "String".
at new GraphQLSchema (D:\Projects\Pinterest Clone\server\node_modules\graphql\type\schema.js:219:15)
at Object.<anonymous> (D:\Projects\Pinterest Clone\server\schemas\schema.js:159:16)
at Module._compile (node:internal/modules/cjs/loader:1149:14)
at Module._extensions..js (node:internal/modules/cjs/loader:1203:10)
at Module.load (node:internal/modules/cjs/loader:1027:32)
at Module._load (node:internal/modules/cjs/loader:868:12)
at Module.require (node:internal/modules/cjs/loader:1051:19)
at require (node:internal/modules/cjs/helpers:103:18)
at Object.<anonymous> (D:\Projects\Pinterest Clone\server\index.js:6:16)
at Module._compile (node:internal/modules/cjs/loader:1149:14)

Node.js v18.10.0

错误原因

核心问题出在PinType定义中,createdAt字段错误使用了原生JavaScript的String类型,而非GraphQL官方提供的GraphQLString类型:

// 错误写法
createdAt: { type: String },

GraphQL会将每个未识别的类型(包括原生JS类型)当作自定义类型处理,当多个地方引用String时,就会重复创建同名类型,触发"uniquely named types"校验错误。

修复方案

修改PinType文件,将createdAt的类型替换为GraphQLString,同时规范循环引用的依赖引入位置:

const { GraphQLObjectType, GraphQLID, GraphQLString } = require('graphql');
const User = require('../models/UserModel');
// 提前引入UserType,避免循环引用延迟问题
const UserType = require('./UserSchema');

const PinType = new GraphQLObjectType({
  name: 'Pin',
  fields: () => ({
    id: { type: GraphQLID },
    title: { type: GraphQLString },
    imageUrl: { type: GraphQLString },
    description: { type: GraphQLString },
    link: { type: GraphQLString },
    user: {
      type: UserType,
      resolve(parent, args) {
        return User.findById(parent.userId);
      },
    },
    // 修复:将String改为GraphQLString
    createdAt: { type: GraphQLString },
  }),
});

module.exports = PinType;

同步调整UserType文件的依赖引入位置:

const {
  GraphQLObjectType,
  GraphQLID,
  GraphQLString,
  GraphQLList,
} = require('graphql');
// 提前引入PinType
const PinType = require('./PinSchema');

const UserType = new GraphQLObjectType({
  name: 'User',
  fields: () => ({
      id: { type: GraphQLID },
      name: { type: GraphQLString },
      userName: { type: GraphQLString },
      createdPins: { type: new GraphQLList(PinType) },
      savedPins: { type: new GraphQLList(PinType) },
  }),
});

module.exports = UserType;

验证步骤

  1. 保存修改后的文件
  2. 重启Node.js服务
  3. 执行GraphQL查询/突变操作,确认报错消失,功能正常运行

内容的提问来源于stack exchange,提问作者Captain X

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.11 22:25:17