【问题标题】:Graphql mutation returning null, but database is updatedGraphql突变返回null,但数据库已更新
【发布时间】:2018-09-17 11:57:43
【问题描述】:

我正在尝试添加一个突变以允许客户端将文档添加到 LineItem 架构。我在下面编写的代码允许我在使用 GraphiQL 对其进行测试时执行此操作,但我得到的响应为空。如何修复代码以使响应成为新文档?

addLineItem: {
    type: LineItemType,
    args: {
      orderId: {type: new GraphQLNonNull(GraphQLID)},
      productId: {type: new GraphQLNonNull(GraphQLID)},
      quantity: {type: new GraphQLNonNull(GraphQLInt)}
    },
    resolve(parent, args) {
      Product.findById(args.productId, (err, result) => {
        let price = result.price;
        let subtotal = price*args.quantity;
        let lineitem = new LineItem({
          orderId : args.orderId,
          productId : args.productId,
          quantity : args.quantity,
          subtotal: subtotal
        });
        return lineitem.save();
    }}
  }
},

【问题讨论】:

    标签: javascript node.js graphql


    【解决方案1】:

    问题是你没有在resolve函数中返回任何值,lineitem.save();返回的是callBack中的值

    制作解析函数async,移除findById callBack 并等待结果,然后执行您的逻辑并返回值,如下所示:

    async resolve(parent, args) {
      const result = await Product.findById(args.productId);
    
      let price = result.price;
      let subtotal = price*args.quantity;
      let lineitem = new LineItem({
        orderId : args.orderId,
        productId : args.productId,
        quantity : args.quantity,
        subtotal: subtotal
      });
    
      return lineitem.save();
    }
    

    【讨论】:

      【解决方案2】:

      其实你的代码没有问题。 .

      您需要将返回值指定为类型(e.g. Boolean, String, etc)。类型可以为空,例如:值可以为空,事实上,它们默认可以为空除非你用 !

      定义它们

      所以 null 返回值没有什么问题。

      【讨论】:

        猜你喜欢
        • 2020-12-22
        • 2019-08-20
        • 2023-01-09
        • 2021-04-01
        • 2019-06-28
        • 2019-11-25
        • 2018-06-06
        • 2019-06-20
        • 2018-06-18
        相关资源
        最近更新 更多