是否可以在同一个对象中有一个 objectType

Is it possible to have an objectType within the same object

我一直在尝试获取它,因此我可以将多个 "trainings" 放入培训类型中,因为一旦用户同时拥有两者,它们就会相互合并。但是我似乎无法让它工作,我对如何去做感到困惑。

这是我的训练模型:

const mongoose = require('mongoose')
const Schema = mongoose.Schema

let trainingSchema = new Schema({
  name: {
    type: String,
    required: true,
    unique: true
  },
  shortHand: {
    type: String,
    required: true,
    unqiue: true
  },
  desc: { type: String },
  office: {
    type: Schema.Types.ObjectId,
    ref: "Office"
  },
  isMerge: { type: Boolean, default: false},
  mergeInto: [{
    type: Schema.Types.ObjectId,
    ref: "Training"
  }]
})

module.exports = mongoose.model('Training', trainingSchema)

这是我的训练对象

/**
 * Defines Training Type
 */
const TrainingType = new GraphQLObjectType({
  name: "Training",
  fields: {
    id: { type: GraphQLID },
    name: { type: GraphQLString },
    shortHand: { type: GraphQLString },
    desc: { type: GraphQLString },
    office: { 
      type: require('./office').OfficeType,
      resolve: async (office) => {
        return await Office.findById(office.office)
      }
    },
    isMerge: { type: GraphQLBoolean },
    mergeInto: { 
      type: new GraphQLList(TrainingType), // This is the error line
      resolve: async (training) => {
        return await Training.find({id: training.id})
      }
    }
  }
})
module.exports.TrainingType = TrainingType

现在显然我得到的错误是未定义 TrainingType,因为我正在尝试使用尚未完全定义的内容。但是我尝试了其他方法,比如创建一个名为 MergesInto 的不同对象类型,然后在另一个对象中使用它。但这也不起作用,因为一个需要另一个,一个必须在另一个之前定义,这将给我错误未定义。我似乎无法弄清楚如何让它工作。这甚至可能吗?

fields 可以是一个对象,也可以是 returns 一个的函数。将其设为函数会延迟函数内部代码的执行,所以可以引用TrainingType变量而不会报错。

const TrainingType = new GraphQLObjectType({
  name: "Training",
  fields: () => ({
    ...
    mergeInto: { 
      type: new GraphQLList(TrainingType),
      ...
    },
  })
})