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

为何Mutation返回null但表单已提交?MongoDB关联问题求助

问题分析与解决方案

核心问题总结

你遇到的data {mutation: null}问题,根源在于代码中的数据类型不匹配、返回结构不一致,以及缺少必要的错误处理,导致GraphQL无法正确返回预期结果。


具体修复步骤

1. 修正Resolver逻辑(关键修复)

你的Mongoose Schema要求email字段存储Client的ObjectId,但Resolver中直接传入了整个client对象,同时返回结构与GraphQL定义不匹配:

createForm = async (parent, input) => {
  // 先校验是否找到对应Client,避免后续报错
  const client = await Client.findOne({ email: input.email });
  if (!client) {
    throw new Error(`未找到邮箱为 ${input.email} 的用户`);
  }

  // 传入Client的ObjectId而非整个对象
  const form = new Form({
    email: client._id,
    newField: input.newField
  });

  // 直接返回保存后的文档,匹配GraphQL的Form类型定义
  return form.save();
};

2. 优化Mongoose Schema(可选但推荐)

手动指定_id字段会增加不必要的复杂度,Mongoose会自动生成唯一ID,建议移除:

const mongoose = require('mongoose');

const FormSchema = new mongoose.Schema({
  email: {
    type: mongoose.Types.ObjectId,
    ref: 'Client',
    required: true
  },
  newField: {
    type: Number,
    required: true
  }
});

module.exports = mongoose.model('Form', FormSchema);

3. 前端增加输入验证

确保newField是有效数字,避免因NaN导致保存失败:

const newFieldValue = parseInt(formInput.current.value, 10);
if (isNaN(newFieldValue)) {
  alert('请输入有效的数字');
  return;
}

const response = await createExpectation({
  variables: {
    email: selectedClient.map(client => client.value)[0],
    newField: newFieldValue
  }
});

4. 确认Client类型定义

确保GraphQL中已正确定义Client类型,否则Form中的email字段无法正确关联解析:

type Client {
  id: ID!
  email: String!
}

type Form {
  id: ID!
  email: Client!
  newField: Int
}

为什么之前返回null?

当Resolver中出现未捕获的错误(比如找不到Client时访问client._id抛出异常),GraphQL会默认返回null作为mutation结果。建议查看服务器端日志,能直接定位具体报错信息。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 09:01:08