【问题标题】:How do I accept an array of strings using Apollo Server and GQL?如何使用 Apollo Server 和 GQL 接受字符串数组?
【发布时间】:2021-06-19 08:00:48
【问题描述】:

我目前有一个具有自定义 Books 类型的 typeDefs 文件。这就是它目前的样子:

type: Books {
   bookId: String
   authors: [String]
   description: String
   title: String
}

我正在使用 MongoDB 来存储我的数据。我的模型如下所示:

const bookSchema = new Schema({
  authors: [
    {
      type: String,
    },
  ],
  description: {
    type: String,
    required: true,
  },
  // saved book id from GoogleBooks
  bookId: {
    type: String,
    required: true,
  },
  title: {
    type: String,
    required: true,
  }
});

我的解析器看起来像这样:

saveBook: async (parent, args, context) => {
            if (context.user) {
                const book = await Book.create({ ...args })

                await User.findByIdAndUpdate(
                    { _id: context.user._id },
                    { $addToSet: { savedBooks: { bookId: args.bookId } } },
                    { new: true }
                );

                return book;
            }

            throw new AuthenticationError('You need to be logged in!');
        }, 

当我使用 graphql Playground 并在查询变量中发送数据时,我收到一个错误,String cannot represent a non string value: [\"james\", \"jameson\"]", 当我发送时

{
    "input": {
    "bookId": "1",
    "authors": ["james", "jameson"],
    "description": "thdfkdaslkfdklsaf",
    "title": "fdjsalkfj;a",
  }
}

我知道是因为我使用的是字符串数组,将字符串数组输入gql会导致这个错误。我认为如果我在我的 typeDefs 中的字符串周围加上括号,它就会起作用。我似乎找不到将字符串数组发送到 gql 的方法。我浏览了文档,找不到完成此操作的方法..

【问题讨论】:

    标签: arrays mongodb graphql


    【解决方案1】:

    从作者中创建一个类型定义,然后将书籍中的作者变量指定为“作者”类型。

    如果我没记错的话,我认为您还必须在 bookschema 中定义数组。

    并且不要忘记确保数据库中的模型命名必须与代码中的相同。

    像这样:

    type: Author {
       name: String
    }
    
    type: Books {
       bookId: String
       authors: [Author]
       description: String
       title: String
    }
    
    const bookSchema = new Schema({
      authors: [
        {
          type: Author,
        },
      ],
      description: {
        type: String,
        required: true,
      },
      // saved book id from GoogleBooks
      bookId: {
        type: String,
        required: true,
      },
      title: {
        type: String,
        required: true,
      }
    });
    

    希望这可行:)

    【讨论】:

      猜你喜欢
      • 2019-09-11
      • 1970-01-01
      • 2021-04-19
      • 1970-01-01
      • 2013-05-28
      • 1970-01-01
      • 1970-01-01
      • 2019-02-06
      • 2016-07-18
      相关资源
      最近更新 更多