mongodb - 如何处理 GraphQL 架构定义中的连字符

标签 mongodb mongoose graphql mongoose-schema graphql-js

我的 Mongoose 架构如下

var ImageFormats = new Schema({
     svg        : String,
     png-xlarge : String,
     png-small  : String
});

当我将其转换为 GraphQL 架构时,这就是我尝试的

export var GQImageFormatsType: ObjectType = new ObjectType({
     name: 'ImageFormats',

     fields: {
          svg        : { type: GraphQLString },
         'png-xlarge': { type: GraphQLString },
         'png-small' : { type: GraphQLString }
 }
});

GraphQL 返回以下错误:错误:名称必须匹配/^[_a-zA-Z][_a-zA-Z0-9]*$/但“png-xlarge”不匹配。

如果我尝试在 Mongoose 模型之后对 GraphQL 进行建模,如何协调这些字段?有没有办法让我创建别名?

(我在涂鸦和 stackoverflow 论坛上搜索过这个问题,但找不到类似的问题)

最佳答案

GraphQL Returns the following error: Error: Names must match /^[_a-zA-Z][_a-zA-Z0-9]*$/ but "png-xlarge" does not.

GraphQL 提示字段名称 'png-xlarge' 无效。错误消息中的正则表达式表示第一个字符可以是字母,无论大小写或下划线。其余字符也可以有数字。因此,很明显,连字符 - 和单引号 ' 都 Not Acceptable 作为字段名称。这些规则基本上遵循几乎在每种编程语言中都可以找到的变量命名规则。您可以查看GraphQL naming rules .

If I am trying to model the GraphQL after my Mongoose model, how can I reconcile the fields? Is there a way for me to create an alias?

借助resolve函数,您可以执行以下操作:

pngXLarge: { 
    type: GraphQLString,
    resolve: (imageFormats) => {
        // get the value `xlarge` from the passed mongoose object 'imageFormats'
        const xlarge = imageFormats['png-xlarge'];
        return xlarge;
    },
},

关于mongodb - 如何处理 GraphQL 架构定义中的连字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41427320/

相关文章:

node.js - 选择与查找以及在 Mongoose 中查找的位置

mongodb - 在 mongodb 中对推送的数组进行排序

node.js - Mongodb根据id获取数组中其他集合数据的个数

graphql - 如何在graphql查询过滤器中使用OR/AND或使大小写不敏感的过滤器?

graphql - Strapi v4 嵌套数据过多

javascript - 具有 React 的 Apollo 客户端 2 无法进行查询

java - Spring Boot MongoRepository 空指针异常

c# - Aggregate() 的 MongoDB 结果集

java - MongoDB Morphia save() 生成两个具有相同 ID 的对象

javascript - 陷入实现嵌套数据过滤循环的困境,这可能是一种更优雅的方法吗?