代码之家  ›  专栏  ›  技术社区  ›  Mendes

GraphQL和Mongoose纯对象(lean()查询)

  •  0
  • Mendes  · 技术社区  · 6 年前

    考虑以下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 graphqlist(usertype), description:“获取所有用户”, 解析(根、参数、上下文){ return 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 回复  |  直到 6 年前