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

TypeGraphQL+Typegoose报错:非空字段UserEntity.id不能返回null

解决TypeGraphQL + Typegoose中UserEntity.id返回null的问题

问题核心是TypeGraphQL默认不会自动识别Typegoose生成的id getter,必须手动用装饰器把这个字段暴露给GraphQL,并确保它能正确映射MongoDB的_id。

解决步骤与所需装饰器

你需要组合使用TypeGraphQL的@Field和Typegoose的@prop装饰器,两种实现方式任选其一:

方式1:使用Typegoose虚拟属性映射_id到id

import { ObjectType, Field, ID } from "type-graphql";
import { prop, getModelForClass } from "@typegoose/typegoose";
import mongoose from "mongoose";

@ObjectType()
export class UserEntity {
  // 用@Field标记为GraphQL的ID类型字段
  @Field(() => ID)
  // 定义虚拟属性,自动将_id转为字符串形式的id
  @prop({
    type: String,
    virtual: true,
    get(this: UserEntity) {
      return this._id?.toString();
    },
  })
  id!: string;

  // MongoDB原生的_id字段,无需暴露给GraphQL,所以不加@Field
  @prop()
  _id?: mongoose.Types.ObjectId;

  // 其他业务字段示例
  @Field()
  @prop({ required: true })
  username!: string;

  @Field()
  @prop({ required: true })
  email!: string;
}

export const UserModel = getModelForClass(UserEntity);

方式2:通过类getter暴露id字段

import { ObjectType, Field, ID } from "type-graphql";
import { prop, getModelForClass } from "@typegoose/typegoose";
import mongoose from "mongoose";

@ObjectType()
export class UserEntity {
  @prop()
  _id?: mongoose.Types.ObjectId;

  // 用@Field标记为GraphQL字段,同时通过getter返回_id的字符串形式
  @Field(() => ID)
  get id(): string {
    // 兜底空字符串避免null,也可以根据需求抛出错误
    return this._id?.toString() || "";
  }

  // 其他业务字段...
  @Field()
  @prop({ required: true })
  username!: string;
}

export const UserModel = getModelForClass(UserEntity);

原理说明

  • Typegoose会自动给实体实例添加id getter,但这个属性默认不会被TypeGraphQL扫描为GraphQL字段,必须用@Field明确标记。
  • 两种方式都是让id字段返回MongoDB_id的字符串形式,确保GraphQL查询时能拿到非空值,避免触发"Cannot return null for non-nullable field"异常。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.24 17:22:16