最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

运维笔记admin22浏览0评论

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

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. 暂无评论