如何为MongoDB嵌套数据定义GraphQLObjectType及对象列表类型?
解决GraphQL嵌套MongoDB数据的类型定义问题
要获取嵌套的documents数据,你需要先为单个文档定义对应的GraphQL对象类型,再用GraphQLList包裹这个类型来描述数组结构。具体步骤如下:
1. 定义单个文档的GraphQL类型
首先创建一个GraphQLObjectType,用来描述MongoDB中documents数组里每一项的结构。比如假设你的文档包含id、title、fileUrl和createdAt字段,代码如下:
const DocumentType = new GraphQLObjectType({ name: 'Document', // 这个名称要唯一,会用于GraphQL schema中 fields: () => ({ id: { type: GraphQLID, description: 'Unique ID of the document' }, title: { type: GraphQLString, description: 'Title of the document' }, fileUrl: { type: GraphQLString, description: 'URL to the document file' }, createdAt: { type: GraphQLString, description: 'Creation date of the document' } // 这里根据你MongoDB里实际的文档字段添加,有嵌套对象的话继续定义对应的类型 }) });
2. 在Person类型中引用这个文档类型
接下来修改你原来的fields配置,把documents的类型指定为GraphQLList(DocumentType),同时如果需要手动处理数据返回(比如从MongoDB查询后映射),可以添加resolve函数:
fields() { return { name: { type: GraphQLString, description: 'Name of the person' }, age: { type: GraphQLString, description: 'Age' }, documents: { type: new GraphQLList(DocumentType), // 这里传入定义好的DocumentType description: 'All documents for the person', // 如果你的parent对象(当前的person)已经包含documents数组,resolve可以直接返回 resolve(parent) { return parent.documents; } } } }
关键说明
GraphQL是强类型的,必须明确告知每个字段的具体结构——你之前只写了new GraphQLList()但没有指定数组元素的类型,所以GraphQL无法识别嵌套数据的结构,自然无法返回这部分内容。
如果你的documents里还有更深层次的嵌套对象(比如每个文档里有metadata子对象),只需要重复这个过程:先定义MetadataType,再在DocumentType的fields里引用它即可。
内容的提问来源于stack exchange,提问作者Jayanta Baishya
相关产品推荐
相关产品推荐

