GraphQL +猫鼬:如何更改猫鼬检索数据的属性

时间:2018-12-21 14:34:22

标签: javascript node.js mongodb mongoose graphql

我正在编写一个GraphQL查询,该查询将返回猫鼬数据:

export const getInventory = () => {
    let query = {
        deletedAt: null
    };

    let stocks = await StockModel.find(query)
        .sort({ material: 1 });

    // Now separate each inventory item per material
    let inventory = {};
    stocks.map(stock => {
        if (inventory[stock.material]) {
            inventory[stock.material].quantity += stock.quantity;
        } else {

            let clone = Object.assign({}, stock);
            clone.lot = null;
            clone.expirationDateTime = null;
            clone.partNumber = null;
            clone.manufacturer = null;

            inventory[stock.material] = clone;
        }
    });

    let list = Object.keys(inventory).map(key => {
        return inventory[key];
    });

    return list;
};

这是我的库存GraphQL查询:

const inventory = {
    type: new GraphQLList(StockType),
    description: "Get all inventory",
    resolve(root, args, context) {
        return getInventory();
    }
};

运行以下查询时:

{
  viewer {
    inventory() {
      id
      quantity
      lot
    }
  }
}

我收到以下GraphQL错误:

{
  "errors": [
    {
      "message": "Expected value of type \"Stock\" but got: [object Object].",
      "locations": [
        {
          "line": 3,
          "column": 5
        }
      ],
      "stack": "Expected value of type \"Stock\" but got: [object Object].\n\nGraphQL request (3:5)\n2:   viewer {\n3:     inventory {\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",
        "inventory",
        0
      ]
    }

}

感谢您帮助解决该错误:

0 个答案:

没有答案