繁体   English   中英

Graphql突变返回null,但数据库已更新

[英]Graphql mutation returning null, but database is updated

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

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();
    }}
  }
},

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

使resolve函数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();
}

实际上,您的代码没有错。

您需要指定一个返回值作为类型(eg Boolean, String, etc) 类型可以是可空的,例如:值可以为空,并且实际上,默认情况下它们是可空的, 除非您使用!定义它们。

因此返回空值没有错。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM