MERN栈健身计划构建器addExcercise突变报错及功能问题
解决MERN栈健身计划构建器addExercise突变的两个问题
1. 修复「AuthenticationError is not a constructor」错误
这个错误几乎都是AuthenticationError导入方式错误导致的,按你的Apollo Server版本调整导入语句:
- 若使用Apollo Server v4+(
@apollo/server):
const { AuthenticationError } = require('@apollo/server'); // ES模块写法 import { AuthenticationError } from '@apollo/server';
- 若使用旧版
apollo-server-express:
const { AuthenticationError } = require('apollo-server-express');
同时确保你的auth.js中间件正确抛出错误:
// auth.js示例 const { AuthenticationError } = require('@apollo/server'); module.exports = (context) => { if (!context.user) { throw new AuthenticationError('需登录后操作'); } return context.user; };
2. 修复addExercise无法向Workout的exercises数组添加内容的问题
从Mongoose更新逻辑、Schema定义、参数传递三个维度排查:
检查Mongoose更新语句
必须用$push操作符向数组添加元素,同时验证训练计划归属当前用户,避免越权:
// addExercise resolver示例 addExercise: async (_, { workoutId, exercise }, context) => { const user = auth(context); // 只更新当前用户名下的训练计划,返回更新后的文档 const updatedWorkout = await Workout.findOneAndUpdate( { _id: workoutId, userId: user._id }, { $push: { exercises: exercise } }, { new: true, runValidators: true } // runValidators确保符合Schema校验 ); if (!updatedWorkout) { throw new Error('未找到目标训练计划,或无修改权限'); } return updatedWorkout; }
确认GraphQL Schema定义
确保Workout的exercises是数组类型,且addExercise的参数结构匹配:
type Workout { _id: ID! userId: ID! name: String! exercises: [Exercise!]! } type Mutation { addExercise(workoutId: ID!, exercise: ExerciseInput!): Workout! } input ExerciseInput { name: String! sets: Int! reps: Int! weight: Float }
验证前端参数传递
确保调用突变时,workoutId和exercise参数格式正确,比如:
// 前端调用示例 const ADD_EXERCISE = gql` mutation AddExercise($workoutId: ID!, $exercise: ExerciseInput!) { addExercise(workoutId: $workoutId, exercise: $exercise) { _id exercises { name sets } } } `; client.mutate({ mutation: ADD_EXERCISE, variables: { workoutId: '目标训练计划ID', exercise: { name: '杠铃卧推', sets: 4, reps: 8, weight: 85 } } });
额外排查点
- 确认
Workout模型包含userId字段,关联到创建该计划的用户; - 在resolver中添加
console.log(workoutId, user._id, exercise),检查参数是否正确接收; - 直接在MongoDB中查询目标
Workout文档,确认exercises数组初始结构是否正常。
内容的提问来源于stack exchange,提问作者EvanFodemski
相关产品推荐
相关产品推荐

