【问题标题】:Graphql mongodb cannot return _idGraphql mongodb 无法返回 _id
【发布时间】:2021-02-25 09:42:48
【问题描述】:

大家好,我正在使用 graphql 和 mongodb 创建一个 api。我正在使用 mongodb 聚合来过滤我的文档。

export const findAllVariants = async (_, { orderby, filter, skip, sort, perPage }, context) => {
  await jwtAuthentication.verifyTokenMiddleware(context);

  try {
    const aggregate = Variant.aggregate();
    const match = { $and: [] };

    if (filter) {
      await filter.split(' ').forEach((f) => {
        match.$and.push({
          $or: [
            {
              color: {
                $regex: new RegExp(transliterate(f), 'i')
              }
            },
            {
              size: {
                $regex: new RegExp(transliterate(f), 'i')
              }
            },
            {
              sku: {
                $regex: new RegExp(transliterate(f), 'i')
              }
            },
            {
              barcode: {
                $regex: new RegExp(transliterate(f), 'i')
              }
            }
          ]
        });
      });
      aggregate.match(match);
    }

    const options = {
      allowDiskUse: true,
      limit: perPage,
      page: skip,
      sortBy: { [orderby]: sort }
    };

    return Variant.aggregatePaginate(aggregate, options, (err, results, pageCount, count) => {
      if (err) {
        return new ApolloError(`There was an error ${err}`);
      }
      console.log(results);
      return {
        count,
        variants: results,
        pageCount,
        skip
      };
    });
  } catch (err) {
    return new ApolloError(`There was an error ${err}`);
  }
};

我的graphql def是这个

export default gql`
  type VariantsResult {
    variants: [Variant]
    count: Int
    pageCount: Int
    skip: Int
  }

  type Variant {
    id: String!
    color: String
    size: String
    quantity: Int
    sku: String
    barcode: String
    price: Price
    images: [String]
  }

  input VariantInfo {
    id: ID!
    color: String!
    size: String!
    quantity: Int
    sku: String!
    barcode: String!
    price: InputPrice!
    images: [ImageInfo]!
  }

  extend type Query {
    findAllVariants(orderby: Int, filter: String, skip: Int, sort: Int, perPage: Int): VariantsResult
  }

  extend type Mutation {
    createVariant(variantInfo: VariantInfo): Variant!
    removeVariantFromProduct(variantInfo: VariantInfo, productInfo: ProductInfo): Product!
    addVariantToProduct(variantInfo: VariantInfo, productInfo: ProductInfo): Product!
    editVariantFromProduct(variantInfo: VariantInfo): Variant!
  }
`;

现在在阿波罗操场上,当我提供所需的数据并返回 id 值时,它会显示以下消息“无法为不可为空的字段 Variant.id 返回 null。”

这仅发生在 id 字段中,所有其他字段都可以正常工作。 请帮忙!

【问题讨论】:

    标签: node.js mongodb graphql


    【解决方案1】:

    错误:

    身份证!表示该字段不可为空 (https://graphql.org/learn/schema/):

    id: ID!
    

    在您的情况下,Variant.id 为 null(抛出错误)。

    在 GraphQL 中使用可空性https://www.apollographql.com/blog/using-nullability-in-graphql-2254f84c4ed7/

    可能的解决方案:

    Mongodb 使用_id 而不是id

    类型可以是:

    type Player{
      _id: String
      name: String
      salary: String
    }
    

    通过 id 获取数据可能如下所示 (ObjectID docs):

    db.collection('baseballPlayers').findOne({ _id: ObjectID("5faeda2c7e348a5e142827ae") });
    

    compass

    Sum: 从简单的 Query by id 开始(在你进入聚合之前)并检查返回值是否为 null(或不是)。然后在 _id 字段解析器中使用正确的查询。

    相关问题:

    相关教程:

    【讨论】:

      猜你喜欢
      • 2018-08-25
      • 1970-01-01
      • 1970-01-01
      • 2018-09-07
      • 2017-07-22
      • 2019-05-03
      • 1970-01-01
      • 2017-08-10
      • 1970-01-01
      相关资源
      最近更新 更多