【问题标题】:Why is my resolver not returning the first time?为什么我的解析器没有第一次返回?
【发布时间】:2018-12-05 10:25:05
【问题描述】:

我正在构建一个 GraphQL 服务器,但我的一个解析器出现了一些奇怪的行为。第一次运行突变时,它返回 null,但是当我使用日志记录时,控制台清楚地显示该对象在我尝试返回之前已由 Mongoose 返回。

解析器:

setView(error, { name, author, data }) {
    if (error) return console.error(error);
    console.log(`Creating new view named: ${name}`);
    let newView = new View({ name: name, author: author, data: data });
    newView.save();
    console.log("View created");
    console.log(View.findOne({ name: name }));
    return View.findOne({ name: name });
}

控制台日志:

创建名为:testView5 的新视图

视图已创建

model.Query {_mongooseOptions: 对象, mongooseCollection: NativeCollection,模型:,架构:架构,操作:“findOne”,...}

创建名为:testView5 的新视图

视图已创建

model.Query {_mongooseOptions: 对象, mongooseCollection: NativeCollection,模型:,架构:架构,操作:“findOne”,...}

突变:

mutation {
  setView(
    name: "testView7",
    author: "Bob", 
    data: [
        "First Column", 
        "Second Column", 
        "Third Column"
    ]) {
    name
  }
}

初始返回:

{
  "data": {
    "setView": null
  }
}

后续返回(同样的变异再次运行):

{
  "data": {
    "setView": {
      "name": "testView7"
    }
  }
}

目前,我想知道这是否与我使用 findOne 返回的方式有关,但我不明白如果它第二次起作用会是什么。

【问题讨论】:

  • 如果它是一个新项目,您必须通过 {new: true } 才能返回新项目
  • 除非我遗漏了一些适用于 findOneAndUpdate 的东西,而不是适用于 findOne。
  • 是的,保存是一个异步操作,所以我假设你运行 find 时没有保存文档

标签: javascript mongoose graphql apollo


【解决方案1】:

Joe Warner 在上面说保存是异步的时是正确的。解决方案是让函数等待来自保存的承诺,如下所示:

    async setView(error, { name, author, data }) {
        if (error) return console.error(error);
        console.log(`Creating new view named: ${name}`);
        let newView = new View({ name: name, author: author, data: data });
        var result = await newView.save();
        console.log(`Created view: ${result}`);
        return result;
    }

【讨论】:

  • 很高兴为您提供帮助 :)
猜你喜欢
  • 2021-11-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-05-29
  • 1970-01-01
  • 1970-01-01
  • 2018-11-25
相关资源
最近更新 更多