读取嵌套对象

时间:2018-05-01 23:43:00

标签: javascript node.js mongodb mongoose graphql

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

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!
}

一旦我尝试查询它:

{
  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文档和ids看起来没问题。我想这是我模特的错。

如果你想仔细看看project repo

1 个答案:

答案 0 :(得分:1)

<强> SOLUTION:

返回值中的垃圾ID是由嵌套实体中的不填充填充引起的。我设法解决问题的方式:

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