mongodb - 在 GraphQL 和 Apollo 中检索数组
问题描述
因此,我使用 Graphql 和 apollo 设置了一个 api,并设法将字符串数组导入 mongoDB ...现在我正在使用 Apollo 查询数据以做出反应,并且似乎无法找到如何检索它,因为我得到了
error:[GraphQL error]: Message: String cannot represent an array value: [pushups,situps], Location: [object Object], Path: wods,0,movements
我的架构设置为:
const WodType = new GraphQLObjectType({
name: 'Wod',
fields: () => ({
id: { type: GraphQLID },
name: { type: GraphQLString },
movements: { type: GraphQLString },
difficulty: { type: GraphQLString },
group: {
type: GroupType,
resolve(parent, args) {
return Group.findById(parent.groupId);
}
}
}) });
我的突变为:
const Mutation = new GraphQLObjectType({
name: 'Mutation',
fields: {
addWod: {
type: WodType,
args: {
name: { type: new GraphQLNonNull(GraphQLString) },
movements: { type: new GraphQLList(GraphQLString) },
difficulty: { type: new GraphQLNonNull(GraphQLString) },
groupId: { type: new GraphQLNonNull(GraphQLID) }
},
resolve(parent, args) {
let wod = new Wod({
// Use model to create new Wod
name: args.name,
movements: args.movements,
difficulty: args.difficulty,
groupId: args.groupId
});
// Save to database
return wod.save();
}
该数组是“运动”下的字符串数组......非常感谢任何有助于将其放入 React 的查询......这是前端的当前查询......使用 Apollo Boost
const getWodsQuery = gql`
{
wods {
id
name
movements
difficulty
}
}
`;
解决方案
不确定它是否仍然相关,我没有重新创建代码,但问题可能是,您将“运动”作为“字符串”返回,而不是输出对象类型 Wod 中的字符串数组。这只是基于您传递给突变的参数(即字符串列表)做出的假设。修复应该只是修改 Wood 类型如下
const WodType = new GraphQLObjectType({
name: 'Wod',
fields: () => ({
id: { type: GraphQLID },
name: { type: GraphQLString },
movements: { type: new GraphQLList(GraphQLString) },
difficulty: { type: GraphQLString },
group: {
type: GroupType,
resolve(parent, args) {
return Group.findById(parent.groupId);
}
})
请注意,这只是我的假设,因为我不知道您的数据是如何存储的,但根据错误消息它可能是正确的。我写了一篇关于在 GraphQL 模式中实现列表/数组的文章,因为我看到很多人都在为类似的问题而苦苦挣扎。你可以在这里查看https://graphqlmastery.com/blog/graphql-list-how-to-use-arrays-in-graphql-schema
推荐阅读
- python - python data not insert into sqlite database errors found
- excel - $BSE = $BSECollection[$BSEindex - 1]; ErrorException Undefined offset: -1 Laravel
- java - How do I reorder a linked list?
- java - 在将输入作为变量从java传递给存储过程之前对其进行清理
- javascript - 如何使用 javascript 或 jquery 在单个文本字段中验证多个电子邮件地址
- r - 您如何在嵌套在 tibbles 中的许多模型上执行 predict.gam?
- python - 本地主机上的 Django enctype=multipart/form-data 返回白屏
- r - 编写一个 R 函数来检查一个矩阵是否只包含 0 和 1
- php - 如何在 MVC 中使用 $_GET 从 url 获取数据?
- php - 如何计算跨数据库行的平均值?