Graphql无法按预期解析

时间:2018-08-16 01:06:27

标签: node.js graphql apollo graphql-js apollo-server

我正在开发GraqphQL-API,该API通过Mongoose从MongoDB中获取数据。现在,我遇到了一个问题,即GraphQL不使用查询来解析字段,而是使用了没有设置ID的字段解析器。

TypeDefs:

type Query{      
  getUser(user_id: String!): User
  getGroup(group_id: String!): Group    
}
type Group {
  name: String
  scopes: [Scope]
  id: String
}

解析器:

Query: {
  getUser: (root,args,context) => {
     console.log(args);
     return getUser(args.user_id);
  },
   getGroup: (root,args,context) => {
     return getGroup(args.group_id);
   }
},
Group: {
  scopes(group){
     return getScopes(group.id);
  },
  name(group){
       return getGroupName(group.id);
  }
},

功能:

exports.getGroup = async (id) => {

const g = await Group.findOne({_id:id});
const scopes = [];
for(let index in g.scopes){
    scopes.push({id: g.scopes[index]});
}
console.log(g.name);
return{
    name: g.name,
    scopes: scopes
};
};
exports.getGroupName = async (id) => {

const g = await Group.findOne({_id:id});
console.log(id);
return g.name;
};

exports.getScopes = async (id) => {

const g = await Group.findOne({_id:id});
const scopes = [];
for(let index in g.scopes){
    scopes.push({id: g.scopes[index]});
}
return scopes;
};

查询:

 query getUserGroup{
      getGroup(group_id:"5b74c537086152554adf818e"){name}           
 }

结果:

{
"data": {
  "getGroup": {
    "name": null
  }
},
"errors": [
  {
    "message": "Cannot read property 'name' of null",
    "locations": [
      {
        "line": 3,
        "column": 5
      }
    ],
    "path": [
      "getGroup",
      "name"
    ],
    "extensions": {
      "code": "INTERNAL_SERVER_ERROR",
      "exception": {
        "stacktrace": [
          "TypeError: Cannot read property 'name' of null",
          "    at _callee2$ (/XXXX/resolver/group.js:20:14)",
          "    at tryCatch (/XXXX/node_modules/regenerator- 
          runtime/runtime.js:65:40)",
          "    at Generator.invoke [as _invoke] 
          (XXXX/node_modules/regenerator-runtime/runtime.js:303:22)",
          "    at Generator.prototype.(anonymous function) [as next] 
          (XXXXX/node_modules/regenerator-runtime/runtime.js:117:21)",
          "    at step (XXXXX/src/resolver/group.js:5:191)",
          "    at XXXX/resolver/group.js:5:361",
          "    at <anonymous>"
      ]
    }
  }
}
]
}

1 个答案:

答案 0 :(得分:0)

const g = await Group.findOne({_id:id});

"TypeError: Cannot read property 'name' of null"

"path": [
  "getGroup",
  "name"
],

可以检查g是否存在吗?