【发布时间】:2020-05-29 14:53:03
【问题描述】:
所以我有两个对象类型,我试图将它们包括在内以建立关系,其中一个有效,其中一个只返回一个空对象,我不知道为什么。
这个工作,它控制台记录排名类型并且工作正常
const Rank = require('../model/RankModel')
const { RankType } = require('./rank')
console.log(RankType)
/**
* Defines Branch Type
*/
const BranchType = new GraphQLObjectType({
name: "Branch",
fields: {
id: { type: GraphQLID },
name: { type: GraphQLString },
color: { type: GraphQLString },
ranks: {
type: GraphQLList(RankType),
resolve: async (branch) => {
return await Rank.find({branch: branch.id})
}
}
}
})
module.exports.BranchType = BranchType
这是坏掉的那个
const Rank = require('../model/RankModel')
const Branch = require('../model/BranchModel')
const { BranchType } = require('./branch')
console.log(BranchType)
/**
* Defines Rank Type
*/
const RankType = new GraphQLObjectType({
name: "Rank",
fields: {
id: { type: GraphQLID },
name: { type: GraphQLString },
shortHand: { type: GraphQLString },
branch: {
type: BranchType,
resolve: async (rank) => {
return await Branch.findById(rank.branch)
}
}
}
})
module.exports.RankType = RankType
这给了我“消息”的错误:“Rank.branch 的类型必须是输出类型,但得到:未定义。”
模型/关系:
分支模型:
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
let branchSchema = new Schema({
name: {
type: String,
required: true,
unique: true
},
color: {
type: String,
required: true,
unique: true
},
ranks: [{
type: Schema.Types.ObjectId,
ref: 'Rank'
}]
});
module.exports = mongoose.model('Branch', branchSchema)
排名模型
const mongoose = require('mongoose')
const Schema = mongoose.Schema
let rankSchema = new Schema({
name: {
type: String,
required: true,
unique: true
},
shortHand: {
type: String,
required: true,
unique: true
},
branch: {
type: Schema.Types.ObjectId,
ref: 'Branch'
}
});
module.exports = mongoose.model('Rank', rankSchema);
回答!!!!!!
/**
* Defines Rank Type
*/
const RankType = new GraphQLObjectType({
name: "Rank",
fields: () => ({
id: { type: GraphQLID },
name: { type: GraphQLString },
shortHand: { type: GraphQLString },
branch: {
type: require('./branch').BranchType,
resolve: async (rank) => {
console.log(rank.branch)
return await Branch.findById(rank.branch)
}
}
})
})
module.exports.RankType = RankType
【问题讨论】:
-
您是否尝试使用
rank.branch解析branch字段,该字段正在解析中? -
@xadm 是的,因为 objectID 链接到 rank.branch。但是,当我 console.log BranchType 它在这个 rank.js 文件中返回 undefined 。当我需要它并在我的 user.js 文件中使用 console.log 时,它可以正常工作
-
如何通过读取相同的值来定义值(之前没有定义)?
-
@xadm 我遇到的问题是 {BranchType} 未定义。否则一切都会奏效。出于某种原因,即使我正在导出 const BranchType 它在此特定文件中未定义。当我在另一个文件中需要它时,它工作正常。我只是不知道为什么它会在这个文件中未定义。如果我注释掉 Rank.branch 但 {BranchType} 仍然未定义,它会起作用
-
fields可以使用返回对象的函数来代替对象。fields: () => ({ branch, ... })这会延迟函数内部代码的评估,直到它被调用。因此,例如,您可以在其中调用 require 以延迟其评估,从而避免循环需求。
标签: javascript node.js express graphql graphql-js