最新消息: 电脑我帮您提供丰富的电脑知识,编程学习,软件下载,win7系统下载。

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

IT培训 admin 4浏览 0评论

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

我正在尝试添加一个变异,以允许客户端将文档添加到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();返回callBack中的值

make resolve function 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();
}

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

我正在尝试添加一个变异,以允许客户端将文档添加到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();返回callBack中的值

make resolve function 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();
}
发布评论

评论列表 (0)

  1. 暂无评论