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

Typegoose与TypeGraphQL中@FieldResolver无法获取userId问题

FieldResolver中notice.userId为undefined的排查与解决

可能的原因及解决方案

1. Mongoose Document序列化问题(最常见)

Mongoose的find()方法默认返回Mongoose Document实例,而非普通JavaScript对象。TypeGraphQL通过@Root注入的是这个Document实例,直接访问notice.userId可能无法获取到值(Document的属性通过getter/setter封装,并非直接挂载在实例上)。

解决方法:
在查询时添加.lean()方法,让Mongoose返回普通对象:

@Query(() => [Notice])
async allNotice() {
    return await NoticeModel.find({}).lean();
}

同理,findNoticeByUserId也需要同步修改:

@Query(() => [Notice])
async findNoticeByUserId(@Arg("user_id") user_id: string) {   
    return await NoticeModel.find({userId: user_id}).lean();
}

2. 直接访问Mongoose Document的原始数据

如果不想修改查询逻辑使用.lean(),可以通过Document的_doc属性直接访问数据库原始数据:

@FieldResolver()
async user(@Root() notice: Notice){
    console.log(notice._doc.userId); // 读取原始数据中的userId字段
    return await UserModel.findById(notice._doc.userId);
}

3. 验证自定义装饰器@NField的正确性

你使用了自定义的@NField替代TypeGraphQL官方的@Field,需要确认该装饰器是否正确完成了GraphQL字段与Mongoose Schema的映射,确保userId字段被正确暴露给GraphQL解析器。

4. 检查数据存储的有效性

验证createNotice方法中传入的noticeInfo是否包含有效userId,并且正确赋值给了Notice实例:

@Mutation(() => Notice)
async createNotice(@Arg("noticeInfo") noticeInfo: NoticeInput) {
    console.log("传入的userId:", noticeInfo.userId); // 验证参数是否包含userId
    let notice = new NoticeModel(noticeInfo); // 直接传入对象替代循环赋值,避免遗漏字段
    return await notice.save();
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 12:35:28