Простые объекты GraphQL и Mongoose (запросы lean ()) - PullRequest
0 голосов
/ 21 декабря 2018

Рассмотрим следующий тип 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 = {type: new GraphQLList (UserType), описание: «Получить всех пользователей», решить(root, args, context) {return UserModel.find (). lean (). exec ();<< lean () добавлено}}; </p>

В этом случае я получаю следующую ошибку 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() mongooseвариант?Что нужно сделать, чтобы это заработало?

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...