【发布时间】: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