0

I have this mutation that returns as expected: id, url and description.

  post(parent, args, context, info) {

   const userId = getUserId(context);
   const user = await context.User.findOne({ _id: userId });

   return context.Link.create(
      {
        url: args.url,
        description: args.description,
        postedBy: userId
      },
 }

The problem is when I add this function that successfully update Refs to children

async post(parent,args,context,info){

  const userId = getUserId(context);
  const user = await context.User.findOne({ _id: userId });

  return context.Link.create(
      {
        url: args.url,
        description: args.description,
        postedBy: userId
      },
      **function(error, createdLink) {
        user.links.push(createdLink._id);
        user.save(createdLink);
      }**
    );
}

Everything works perfect in mongoose and mongo, but graphQL returns null:

{
  "data": {
    "post": null
  }
}

What i am doing wrong?

Mike Will
  • 189
  • 15

1 Answers1

0

Don't mix callbacks and Promises -- see Common Scenario #6 here.

As explained here in the docs, passing a callback to the method means the result will be passed to the callback rather than being made available inside the then function of the resulting Query object. Just stick with Promises.

const link = await context.Link.create({
  url: args.url,
  description: args.description,
  postedBy: userId
});

user.links.push(link._id);
await user.save();

return link;
Daniel Rearden
  • 80,636
  • 11
  • 185
  • 183
  • Now that I understood what I was doing wrong, I was able to solve other problems I had with callbacks and promises. Thanks to you I will sleep well tonight! – Mike Will Oct 03 '19 at 18:28