代码之家  ›  专栏  ›  技术社区  ›  Dan Zawadzki

读取嵌套对象中的嵌套对象

  •  3
  • Dan Zawadzki  · 技术社区  · 7 年前

    我的问题是读取嵌套对象的属性,该对象位于其他嵌套对象内。

    图形QL

    type Mapping {
        id: ID!
        partnerSegmentId: ID!
        ctSegmentId: CtSegment!
    }
    
    type PartnerSegment {
        id: ID!
        name: String!
        platformId: Int!
        partner: Partner!
    }
    
    type Partner {
        id: ID!
        name: String!
    }
    

    一旦我尝试像这样查询它:

    {
      allMappings {
        partnerSegmentId {
          id
          name
          partner {
            id
          }
        }
      }
    }
    

    我收到:

    {
      "data": {
        "allMappings": [
          null
        ]
      },
      "errors": [
        {
          "message": "Cannot return null for non-nullable field Partner.name.",
          "locations": [
            {
              "line": 8,
              "column": 9
            }
          ],
          "path": [
            "allMappings",
            0,
            "partnerSegmentId",
            "partner",
            "name"
          ]
        }
      ]
    }
    

    映射架构

    const mappingSchema = new mongoose.Schema(
        {
            partnerSegmentId: {
                type: mongoose.Schema.Types.ObjectId,
                ref: 'PartnerSegment',
                required: [true, 'Mapping must have partner segment id.']
            },
    
            ctSegmentId: {
                type: mongoose.Schema.Types.ObjectId,
                ref: 'CtSegment',
                required: [true, 'Mapping must have CT segment id.']
            }
        },
        { timestamps: true }
    );
    

    我试图分别阅读Partner、PartnerSegment和Mapping模型。一切正常。你知道我应该在哪里查找问题的根源吗?我检查了mongodb文档和ID,看起来不错。我想这是我的模型的错。

    如果你想仔细看看 project repo .

    1 回复  |  直到 7 年前
        1
  •  1
  •   Dan Zawadzki    7 年前

    解决方案:

    返回值中的垃圾Id是由于嵌套实体中没有工作填充而导致的。我解决问题的方法:

    const allMappings = () =>
        Mapping.find({})
            .populate('user')
            .populate('ctSegment')
            .populate({
                path: 'partnerSegment',
                populate: {
                    path: 'partner'
                }
            })
            .exec();