【问题标题】:Getting null when trying to return only single object and not array in graphql for neo4j db在尝试为 neo4j db 仅返回单个对象而不是 graphql 中的数组时获取 null
【发布时间】:2018-02-02 12:11:46
【问题描述】:

我想返回单个对象(不是数组)。当我尝试返回单个对象时,graphql 服务器返回 null。但是在尝试返回数组时似乎工作正常。

这是我的架构示例:

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
   }
 }

但是,它似乎只有在我尝试返回一个数组时才有效(当我尝试像这样更改类型查询的架构时):

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
       }
     )
   }
  )
 },

}

我需要的是返回一个像这样的对象: getAuthorById(作者ID:字符串!):作者

// 而不是这样的数组-> getAuthorById (authorID: String!): [Author]

那么,有人可以告诉我我在这里做错了什么吗?我所需要的只是返回单个对象而不是数组....提前致谢

【问题讨论】:

    标签: neo4j graphql apollo-server


    【解决方案1】:

    问题出在您的解析器中,特别是您正在从解析器返回result.records.map() 的结果。 map() 计算为一个数组(在这种情况下,将内部函数应用于 result 的每个元素。

    相反,您可以只获取Result 流中的第一个Record

    .then( result => {
       return result.records[0].get("a").properties
       }
     )
    

    【讨论】:

    • 谢谢@William,它起作用了...最后,您能否指出任何具体的链接,我可以在其中了解有关这些属性和neo4j文档的更多信息,因为我已经阅读了大多数neo4j博客,但仍然从未像您提供的那样获得有用的见解。再次感谢!
    • 太棒了! Neo4j JavaScript 驱动的文档在这里:neo4j.com/docs/api/javascript-driver/current
    猜你喜欢
    • 2014-03-15
    • 1970-01-01
    • 2019-05-14
    • 1970-01-01
    • 2020-04-08
    • 2014-03-24
    • 2023-04-04
    • 2018-03-29
    • 2020-07-22
    相关资源
    最近更新 更多