Dan Zawadzki
Dan Zawadzki

Reputation: 732

Reading the nested object in the nested object

My problem is reading properties of nested object, which is inside other nested object.

GraphQL

type Mapping {
    id: ID!
    partnerSegmentId: ID!
    ctSegmentId: CtSegment!
}

type PartnerSegment {
    id: ID!
    name: String!
    platformId: Int!
    partner: Partner!
}

type Partner {
    id: ID!
    name: String!
}

Once I try to query it like:

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

I recieve:

{
  "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"
      ]
    }
  ]
}

Mapping schema

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 }
);

I tried to read separately Partner, PartnerSegment and Mapping models. All works fine. Any idea where i should search source of the problem? I've checked mongodb docs and ids looks okay. I suppose it's fault of my model.

If you would like to take a closer look it's project repo.

Upvotes: 3

Views: 243

Answers (1)

Dan Zawadzki
Dan Zawadzki

Reputation: 732

SOLUTION:

Garbage Id in the return value was caused by not working populate in the nested entity. The way I managed to solve the problem:

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

Upvotes: 1

Related Questions