GraphQL和Mongoose普通对象(lean()查询)

时间:2018-12-21 15:31:08

标签: mongodb mongoose graphql

考虑以下GraphQL类型User

export const UserType = new GraphQLObjectType({
    name: "User",
    description: "User",
    interfaces: () => [NodeInterface],
    isTypeOf: value => value instanceof UserModel,
    fields: () => ({
        id: {
            type: new GraphQLNonNull(GraphQLID),
            resolve: obj => dbIdToNodeId(obj._id, "User")
        },
        name: {
            type: new GraphQLNonNull(GraphQLString)
        },
        address: {
            type: GraphQLString
        }
    })
});

export const UserInputType = new GraphQLInputObjectType({
    name: "UserInput",
    description: "User input type",
    fields: () => ({
        name: {
            type: GraphQLString
        },
        address: {
            type: GraphQLString
        }
    })
});

可以使用简单的users查询来查询用户:

const users = {
    type: new GraphQLList(UserType),
    description: "Get all users",
    resolve(root, args, context) {
        return UserModel.find().exec();
    }
};

很好。但是有时我需要使用普通对象(在从数据库读取后并发送到GraphQL之前进行对象调整):

const users = {     类型:new GraphQLList(UserType),     描述:“获取所有用户”,     resolve(root,args,context){         返回UserModel.find()。lean()。exec(); <<添加了lean()     } };

在这种情况下,我收到以下GraphQL错误:

{
  "errors": [
    {
      "message": "Expected value of type \"User\" but got: [object Object].",
      "locations": [
        {
          "line": 3,
          "column": 5
        }
      ],
      "stack": "Expected value of type \"User\" but got: [object Object].\n\nGraphQL request (3:5)\n2:   viewer {\n3:     stocks {\n       ^\n4:       id\n\n    at invalidReturnTypeError (/dev/node_modules/graphql/execution/execute.js:766:10)\n    at completeObjectValue (/dev/node_modules/graphql/execution/execute.js:758:13)\n    at completeValue (/dev/node_modules/graphql/execution/execute.js:660:12)\n    at completeValueWithLocatedError (/dev/node_modules/graphql/execution/execute.js:580:21)\n    at completeValueCatchingError (/dev/node_modules/graphql/execution/execute.js:556:21)\n    at /dev/node_modules/graphql/execution/execute.js:684:25\n    at Array.forEach (<anonymous>)\n    at forEach (/dev/node_modules/iterall/index.js:83:25)\n    at completeListValue (/dev/node_modules/graphql/execution/execute.js:680:24)\n    at completeValue (/dev/node_modules/graphql/execution/execute.js:643:12)\n    at /dev/node_modules/graphql/execution/execute.js:617:14\n    at process._tickCallback (internal/process/next_tick.js:68:7)",
      "path": [
        "viewer",
        "stocks",
        0
      ]
    }
    ...
    ]
}

为什么GraphQL无法处理通过lean()猫鼬选项返回的普通对象?应该怎么做才能使其正常工作?

0 个答案:

没有答案
相关问题