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