在 GraphQL 中处理 Mongoose 填充字段 [英] Handling Mongoose Populated Fields in GraphQL

查看:26
本文介绍了在 GraphQL 中处理 Mongoose 填充字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何表示可以是简单的 ObjectId 字符串或填充的对象实体的字段?

How do I represent a field that could be either a simple ObjectId string or a populated Object Entity?

我有一个代表设备类型"的猫鼬架构,如下所示

I have a Mongoose Schema that represents a 'Device type' as follows

// assetSchema.js

import * as mongoose from 'mongoose'
const Schema = mongoose.Schema;

var Asset = new Schema({  name : String,
                          linked_device: { type: Schema.Types.ObjectId, 
                                           ref: 'Asset'})

export AssetSchema = mongoose.model('Asset', Asset);

我试图将其建模为 GraphQLObjectType,但我对如何允许 linked_ue 字段采用两种类型的值感到困惑,一种是 ObjectId 和其他是一个完整的 Asset 对象(当它被填充时)

I am trying to model this as a GraphQLObjectType but I am stumped on how to allow the linked_ue field take on two types of values, one being an ObjectId and the other being a full Asset Object (when it is populated)

// graphql-asset-type.js

import { GraphQLObjectType, GraphQLString } from 'graphql'

export var GQAssetType = new GraphQLObjectType({
           name: 'Asset',
           fields: () => ({
               name: GraphQLString,
               linked_device: ____________    // stumped by this
});

我研究过联合类型,但问题是联合类型期望将字段规定为其定义的一部分,而在上述情况下,linked_device 下没有字段linked_device 对应一个简单的 ObjectId 时的字段.

I have looked into Union Types but the issue is that a Union Type expects fields to be stipulated as part of its definition, whereas in the case of the above, there are no fields beneath the linked_device field when linked_device corresponds to a simple ObjectId.

有什么想法吗?

推荐答案

其实你可以使用 linked_device 字段.

As a matter of fact, you can use union or interface type for linked_device field.

使用联合类型,你可以实现GQAssetType如下:

Using union type, you can implement GQAssetType as follows:

// graphql-asset-type.js

import { GraphQLObjectType, GraphQLString, GraphQLUnionType } from 'graphql'

var LinkedDeviceType = new GraphQLUnionType({
  name: 'Linked Device',
  types: [ ObjectIdType, GQAssetType ],
  resolveType(value) {
    if (value instanceof ObjectId) {
      return ObjectIdType;
    }
    if (value instanceof Asset) {
      return GQAssetType;
    }
  }
});

export var GQAssetType = new GraphQLObjectType({
  name: 'Asset',
  fields: () => ({
    name: { type: GraphQLString },
    linked_device: { type: LinkedDeviceType },
  })
});

查看这篇关于 GraphQL union 和界面.

Check out this excellent article on GraphQL union and interface.

这篇关于在 GraphQL 中处理 Mongoose 填充字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆