简体   繁体   中英

Graphql mutation returning null, but database is updated

I'm trying to add a mutation to allow for the client to add a document to the LineItem schema. The code I've written below allows me to do that when I test it using GraphiQL, but the response I get is null. How do I fix the code so that the response is the new document?

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

The problem is that you are not returning any value in resolve function, the lineitem.save(); returns the value inside the callBack

make resolve function async , remove the findById callBack and await for the result, then implement your logic and return the value, like below:

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

Actually there is nothing wrong with your code . .

You need to specify a return value as a type (eg Boolean, String, etc) . Types can be nullable, for example: the value can be null, and, in fact, they are nullable by default unless you define them with !

so there is nothing wrong with null return value.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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