在 neo4j db 的 graphql 中尝试 return 只有单个对象而不是数组时获取空值
Getting null when trying to return only single object and not array in graphql for neo4j db
我想 return 单个对象(不是数组)。当我尝试 return 单个 object.But 似乎工作时,graphql 服务器 returning null尝试 return 数组时很好。
这是我的架构示例:
type Author{
authorID: String
label: String
posts: [Post]
}
type Post {
postID: String
label: String
author: Author
}
type Query {
getAuthorById (authorID: String!): Author #-> this does not work
getAuthorById (authorID: String!): [Author] #-> this works
}
但是当我尝试 运行 这个查询“getAuthorById (authorID: String!)”时,我得到以下结果:
{
"data": {
"getAuthorById": {
"label": null,
"authorID": null
}
}
但是,它似乎只有在我尝试 return 数组时才有效(当我尝试像这样更改类型查询的架构时):
type Query {
getAuthorById (authorID: String!): [Author]
}
这是我的resolver.js:
Query: {
getAuthorById(_, params) {
let session = driver.session();
let query = `MATCH (a:Author{ authorID: $authorID}) RETURN a ;`
return session.run(query, params)
.then( result => {
return result.records.map( record => {
return record.get("a").properties
}
)
}
)
},
}
我需要的是 return 像这样的单个对象:
getAuthorById (authorID: String!): 作者
// 而不是像这样的数组-> getAuthorById (authorID: String!): [Author]
所以,有人可以让我知道我在这里做错了什么吗?我只需要return单个对象而不是数组....谢谢前进
问题出在您的解析器中,特别是您从解析器返回 result.records.map()
的结果。 map()
求值为一个数组(在这种情况下,将内部函数应用于 result
的每个元素。
相反,您可以只获取 Result
流中的第一个 Record
:
.then( result => {
return result.records[0].get("a").properties
}
)
我想 return 单个对象(不是数组)。当我尝试 return 单个 object.But 似乎工作时,graphql 服务器 returning null尝试 return 数组时很好。
这是我的架构示例:
type Author{
authorID: String
label: String
posts: [Post]
}
type Post {
postID: String
label: String
author: Author
}
type Query {
getAuthorById (authorID: String!): Author #-> this does not work
getAuthorById (authorID: String!): [Author] #-> this works
}
但是当我尝试 运行 这个查询“getAuthorById (authorID: String!)”时,我得到以下结果:
{
"data": {
"getAuthorById": {
"label": null,
"authorID": null
}
}
但是,它似乎只有在我尝试 return 数组时才有效(当我尝试像这样更改类型查询的架构时):
type Query {
getAuthorById (authorID: String!): [Author]
}
这是我的resolver.js:
Query: {
getAuthorById(_, params) {
let session = driver.session();
let query = `MATCH (a:Author{ authorID: $authorID}) RETURN a ;`
return session.run(query, params)
.then( result => {
return result.records.map( record => {
return record.get("a").properties
}
)
}
)
},
}
我需要的是 return 像这样的单个对象: getAuthorById (authorID: String!): 作者
// 而不是像这样的数组-> getAuthorById (authorID: String!): [Author]
所以,有人可以让我知道我在这里做错了什么吗?我只需要return单个对象而不是数组....谢谢前进
问题出在您的解析器中,特别是您从解析器返回 result.records.map()
的结果。 map()
求值为一个数组(在这种情况下,将内部函数应用于 result
的每个元素。
相反,您可以只获取 Result
流中的第一个 Record
:
.then( result => {
return result.records[0].get("a").properties
}
)