首页 > 解决方案 > 有没有办法摆脱 GraphQL 中的 [Object: null prototype]

问题描述

Mongoose我正在尝试使用and建立一对多关系数据库GraphQL

每当我将数据插入 GraphQL 突变参数时,都会[Object: null prototype]出错。

[Object: null prototype]当我尝试console.log进行调试时,我注意到该对象将在其前面。

我尝试了很多方法,尝试了map()args 甚至使用replace()但没有运气。我得到的只是"args.ingredient.map/replace is not a function"

我通过更改参数来测试硬编码方法,例如:

args.category = '5c28c79af62fad2514ccc788'
args.ingredient = '5c28c8deb99a9d263462a086'

令人惊讶的是,它适用于这种方法。我假设输入不能是一个对象,而只是一个 ID。

参考下面的实际结果。

解析器

Query: {
    recipes: async (root, args, { req }, info) => {
        return Recipe.find({}).populate('ingredient category', 'name createdAt').exec().then(docs => docs.map(x => x))
    },
},
Mutation: {
    addRecipe: async (root, args, { req }, info) => {
      // args.category = '5c28c79af62fad2514ccc788'
      // args.ingredient = '5c28c8deb99a9d263462a086'
      // console.log(args.map(x => x))
      return Recipe.create(args)
    }
}

类型定义

extend type Mutation {
    addRecipe(name: String!, direction: [String!]!, ingredient: [IngredientInput], category: [CategoryInput]): Recipe
}

type Recipe {
    id: ID!
    name: String!
    direction: [String!]!
    ingredient: [Ingredient!]!
    category: [Category!]!
}

input IngredientInput {
    id: ID!
}

input CategoryInput {
    id: ID!
}

楷模

const recipeSchema = new mongoose.Schema({
    name: String,
    direction: [String],
    ingredient: [{ type: mongoose.Schema.Types.ObjectId, ref: 'Ingredient' }],
    category: { type: mongoose.Schema.Types.ObjectId, ref: 'Category' }
}, {
    timestamps: true // createdAt, updateAt
})

const Recipe = mongoose.model('Recipe', recipeSchema)

这是我在插入数据时控制台记录 args 的结果

{ 
    name: 'Butter Milk Chicken TEST2',
    direction: [ 'Step1', 'Step2', 'Step3' ],
    ingredient:[[Object: null prototype] { id: '5c28c8d6b99a9d263462a085' }],
    category: [[Object: null prototype] { id: '5c28c79af62fad2514ccc788' }]
}

我想我需要得到这样的东西

{ 
    name: 'Butter Milk Chicken TEST2',
    direction: [ 'Step1', 'Step2', 'Step3' ],
    args.category = ['5c28c79af62fad2514ccc788']
    args.ingredient = ['5c28c8ccb99a9d263462a083', '5c28c8d3b99a9d263462a084', '5c28c8d6b99a9d263462a085']
}

标签: javascriptnode.jsmongoosegraphqlapollo-server

解决方案


您可以执行以下操作,并且 [Object: null prototype] 会消失

const a = JSON.parse(JSON.stringify(args));

args.category

[[Object: null prototype] { id: '5c28c79af62fad2514ccc788' }], 

JSON.parse(JSON.stringify(args.category) 将是 { id: '5c28c79af62fad2514ccc788' }


推荐阅读