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

React-GraphQL-Apollo-Mongoose中Mutation传对象数组触发‘Cannot read property 'get' of undefined’错误

Fixing "Cannot read property 'get' of undefined" When Passing Product Array to GraphQL Mutation

Let’s break down what’s going on here: your database operation succeeds, but GraphQL throws an error because Mongoose fails to process the embedded product array when converting the saved document into a GraphQL-compatible response. The error stack points to a virtual property getter on an embedded document trying to call .get() on an undefined value—so the root issue is almost certainly a mismatch between your Mongoose Order model schema and the GraphQL input structure, or a problematic virtual field in your Mongoose schemas.

Step 1: Verify Your Mongoose Order Model Schema

First, ensure your Mongoose model exactly mirrors the structure you’ve defined in GraphQL. Your GraphQL schema expects product to be an array of objects with prodId and a nested value array—your Mongoose schema needs to use embedded document arrays to match this. Here’s the correct setup:

// Define the nested Value schema first
const ValueSchema = new mongoose.Schema({
  name: String,
  props: String
});

// Define the Product schema (embedded in Order)
const ProductSchema = new mongoose.Schema({
  prodId: String,
  value: [ValueSchema] // Must be a DocumentArray, not a plain array
});

// Define the main Order schema
const OrderSchema = new mongoose.Schema({
  orderId: Number,
  product: [ProductSchema] // Again, use a DocumentArray for embedded products
});

// Create the model
const Order = mongoose.model('Order', OrderSchema);

If your existing model uses plain arrays instead of embedded document schemas, or if field names/types don’t match, Mongoose will struggle to parse incoming data and throw that "get of undefined" error during document conversion.

Step 2: Clean Up Your Resolver Logic

Your current resolver has redundant code, and adding validation can prevent bad data from reaching Mongoose. Update it to:

addOrder(parent, args, context, info) {
  const updateData = {};

  // Only add fields if they're provided and valid
  if (args.orderId !== undefined) {
    updateData.orderId = args.orderId;
  }
  if (args.product && Array.isArray(args.product)) {
    // Filter out invalid product entries to avoid Mongoose parsing issues
    updateData.product = args.product.filter(prod => prod && prod.prodId);
  }

  return context.Order.findOneAndUpdate(
    { orderId: args.orderId },
    { $setOnInsert: updateData },
    { 
      new: true, 
      upsert: true,
      runValidators: true // Critical: ensures data matches your Mongoose schema
    }
  );
}

The runValidators: true flag is key—it makes Mongoose validate the incoming product array against your schema before insertion, catching mismatches early instead of letting them cause cryptic errors later.

Step 3: Check for Problematic Virtual Fields

If you’ve defined virtual properties in your Product or Value Mongoose schemas, double-check their getter functions. For example, a virtual like this would cause exactly the error you’re seeing:

// Bad example—fails if `someProperty` is undefined
ProductSchema.virtual('customField').get(function() {
  return this.someProperty.get();
});

Fix virtual getters to guard against undefined values:

// Fixed version
ProductSchema.virtual('customField').get(function() {
  return this.someProperty ? this.someProperty.get() : null;
});

Testing the Fix

After updating your Mongoose schema and resolver, re-run your mutation with a product array. The error should disappear, and GraphQL will return the saved Order object correctly—Mongoose can now properly process the embedded document array without hitting undefined properties.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.06 22:27:50