【问题标题】:Getting only the first object from an array returned from async operation仅从异步操作返回的数组中获取第一个对象
【发布时间】:2021-03-27 13:49:42
【问题描述】:

我正在为我的应用程序开发后端。我使用 mongoose 和 GraphQL 连接并查询我的 mongoDB 数据库/集合。目前,我正在尝试为我的 GraphQL 解析器创建一个异步函数,该函数可以从用户的日志(如果有的话)中获取用户最近的锻炼。我想出了这个:

async getMostRecentWorkout(_, __, context) {
    const user = checkAuth(context); // checks for and get's authenticated user details

    try {
        const workouts = await Workout.find({ username: user.username }).sort({ createdAt: -1 }); 
        return workouts;
    } catch(err) {
        throw new Error(err);
    }
}

问题是,当我在 GraphQL 操场上运行它时,它会获取所有经过身份验证的用户的锻炼。对于这个查询,我只想获取返回的数组的第一个对象(第一个对象应该始终是最近的锻炼,因为它是排序的)。我尝试过使用return workouts[0],但它返回错误消息"Expected Iterable, but did not find one for field \"Query.getMostRecentWorkout\"."

【问题讨论】:

  • 使用 findOne,如果不为空则返回 [workout]
  • workouts[0] 不是workout[0]?但就像@Nonik 写的那样,你不应该首先从数据库中加载整个锻炼列表。
  • 谢谢@Nonik,这行得通。你介意解释一下为什么它需要放在方括号中吗?
  • @JLI_98 was under Impression error you are getting from GraphQL,它需要数组,如果不是,只返回你的对象,记住处理 null,因为 findOne 如果没有找到就会返回 null跨度>
  • @Bergi,这只是问题中的一个错字。不过,感谢您告诉我有关从数据库加载的信息。

标签: javascript mongoose graphql


【解决方案1】:

所以要获得最近的信息,您必须按您已经完成的 createdAt 进行排序,并使用 limit(1) 从大结果中获得 1 项:

所以你的代码很简单:

async getMostRecentWorkout(_, __, context) {
    const user = checkAuth(context); // checks for and get's authenticated user details
    const query = { username: user.username };
    return (
      await Workout.find(query)
                   .sort({ createdAt: -1 })
                   .limit(1).lean()
    )[0];
}

顺便说一句,如果你从 catch 里面再次抛出它,就不需要 try catch。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-03-30
    • 1970-01-01
    • 1970-01-01
    • 2020-06-28
    • 1970-01-01
    • 2021-06-06
    • 2013-05-31
    相关资源
    最近更新 更多