【问题标题】:GraphQL returns Null in mongoose callback [duplicate]GraphQL 在猫鼬回调中返回 Null [重复]
【发布时间】:2020-02-02 01:48:44
【问题描述】:

我有这个按预期返回的突变:id、url 和描述。

  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
      },
 }

问题是当我添加这个函数成功更新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);
      }**
    );
}

在 mongoose 和 mongo 中一切正常,但 graphQL 返回 null:

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

我做错了什么?

【问题讨论】:

    标签: mongoose graphql


    【解决方案1】:

    不要将回调和 Promise 混为一谈——请参阅常见场景 #6 here

    正如here in the docs 所解释的,将回调传递给方法意味着结果将传递给回调,而不是在生成的查询对象的then 函数中可用。只要坚持承诺。

    const link = await context.Link.create({
      url: args.url,
      description: args.description,
      postedBy: userId
    });
    
    user.links.push(link._id);
    await user.save();
    
    return link;
    

    【讨论】:

    • 现在我明白了我做错了什么,我能够解决我在回调和承诺方面遇到的其他问题。谢谢你,我今晚会睡得很好!
    猜你喜欢
    • 2019-02-08
    • 1970-01-01
    • 2013-09-08
    • 2016-06-20
    • 2019-03-25
    相关资源
    最近更新 更多