在GraphQL中处理猫鼬填充字段

在GraphQL中处理猫鼬填充字段

问题描述:

我如何表示一个可以为简单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字段的"noreferrer>联盟 interface 类型.

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联合的文章和界面.