【问题标题】:graphql query return object with null idgraphql 查询返回具有空 id 的对象
【发布时间】:2019-06-13 09:19:25
【问题描述】:

Graphql 返回带有 null id 的 Oject。 使用 mongodb。

我觉得很奇怪。

如果我删除 MailType id 上的 new GraphQLNonNull(), 它适用于 id: null,另一个领域工作正常。

const MailType = new GraphQLObjectType({
    name: 'Mail',
    fields: () => ({
        id: { type: new GraphQLNonNull(GraphQLID), },
...
})

const Query = {
    mails: {
        type: new GraphQLList(MailType),
        args: {
            senderId: { type: GraphQLID },
            isOffline: { type: GraphQLBoolean },
        },
        async resolve(root, args, req, ctx) {
            if (args.isOffline === false) {
                let a = await model.aggregate([
                  { $match: { isOffline: false } },
                ]);
                let b = await model.find({ isOffline: false });

                console.log(JSON.stringify(a) == JSON.Stringify(b)) /// return true
                return a // error
                return b // working
            }
            return model.find({senderId: args.senderId});
        }
    }
}
// with a
    "errors": [
        {
            "message": "Cannot return null for non-nullable field Mail.id."
        }]

我遇到了 2 个小时的麻烦,但我没有得到答案。 有人可以帮帮我吗?

【问题讨论】:

  • 这只是表示当你返回a时id字段为空,这不应该是因为你将id定义为GraphQLNonNull而导致错误。
  • @Boney a, b 是邮件数组。两者都有有效 id 的邮件。

标签: mongodb graphql aggregate


【解决方案1】:

您的 mongodb 架构中可能有错误,而不是在 graphQl 中。 确保您没有通过 id 键定义您的 id,它应该是 _id

例如,如果您使用的是猫鼬,它可能是这样的:

const MailSchema = new Schema({
  _id: {
    type: String,
    unique: true,
  },
  ....
  ....
});

【讨论】:

    猜你喜欢
    • 2020-10-01
    • 2018-12-19
    • 2020-04-08
    • 1970-01-01
    • 2016-10-24
    • 1970-01-01
    • 2023-03-12
    • 2018-06-18
    • 2019-07-08
    相关资源
    最近更新 更多