我实际上正在使用 Neo4j DB 并使用 neo4j_movie_recommendations 代码中的示例来尝试 GraphQL 和 GraphiQL。我有一个非常奇怪的问题,似乎与 javascript 或 GraphQL 相关。我做了一个简单的查询,虽然我可以看到解析器可以返回数据(使用 console.log),但 GraphQL 返回一个“null”值。以下是代码段:
const resolveFunctions = {
Query: {
allVoters(_, params) {
let session = driver.session();
let query = "MATCH (voter:Voter) RETURN voter;"
return session.run(query, params)
.then(result => {
return result.records.map(record => {
console.log("Voter: " + JSON.stringify(record))
return record.get("voter").properties
})
})
},
},
Voter: {
memberOf(voter) {
let session = driver.session(),
params = { voterid: voter.voterid },
query = `
MATCH (v:Voter)-[:MEMBER_OF]->(g:Group)
WHERE v.voterid = $voterid
RETURN g.name AS groupname;
`
return session
.run(query, params)
.then(result => {
return result.records.map(record => {
console.log("Group Name " + record.get("groupname"))
return record.get("groupname")
})
})
},
console.log 显示正确的值,但 GraphiQL 显示名称、电子邮件......正确,但 memberof 字段显示“null”。谁能看到我在这里做错了什么吗?
这是架构......
export default `
type Voter {
voterid : String!
email : String!
name : String!
nickname : [String]
address : String
altAddress : String
dob : String
profession : String
telephone : String
gender : String
skills : [String]
votesIn : PD
livesIn : PD
memberOf : [Group]
}
type Group {
name : String
location : String
created : String
partof : Division
}
type PD {
number : String
location : String
created : String
description : String
partof : Division
}
type Division {
name : String
created : String
belongsto : Constituency
}
type Constituency {
name : String
created : String
reportsto : Region
}
type Region {
name : String
created : String
reportsto : Exec
}
type Exec {
name : String
created : String
}
type Query {
allVoters: [Voter]!
getVoter(voterid: String!): Voter
}
schema {
query: Query
}
`;
编辑...添加解析器 getvoter 的解析器代码:
getVoter(_, params) {
let session = driver.session();
let query = "MATCH (voter:Voter {voterid: $voterid}) RETURN voter;"
return session.run(query, params)
.then(result => {
return result.records.map(record => {
return record.get("voter").properties
})
})
},
最佳答案
无论您的解析器返回什么,都必须是架构定义的正确类型。如果返回错误的类型(数字而不是字符串),GraphQL 可能会尝试将其强制转换为正确的类型,但在大多数情况下它只会返回 null。
您的 memberOf
字段应该是 Group
对象的数组。但是,在您的解析器中,您似乎返回了一个字符串数组:
return result.records.map(record => {
return record.get("groupname")
})
您需要使用 toObject
方法,或者以其他方式将记录转换为对象,其中的字段与 Group
架构中指定的字段相匹配。
关于javascript - 查询时 GraphiQL 返回 'null',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46136815/