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

标签 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 文档,id 看起来没问题。我想这是我模型的错。

如果你想仔细看看它是project repo .

最佳答案

解决方案:

返回值中的垃圾 ID 是由于在嵌套实体中填充无效造成的。我设法解决问题的方式:

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

关于javascript - 读取嵌套对象中的嵌套对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50125284/

相关文章:

mongodb - mongodb的 Multi-Tenancy 不更新域类的版本列

node.js - Mongoose 发现未返回完整集合

javascript - 从 Tumblr 主题中删除导致 CPU 使用率过高的特定 Javascript 代码

javascript - 如何在 jQuery/Javascript 中获取多个命名查询字符串值?

javascript - Intersection Observer 不与 sibling 一起工作

angularjs - 用于大型项目的 Angular 2 或 NodeJs/Express

javascript - 如何在angularjs中创建项目具有不同 Controller 的列表

Javascript 在 JSON 中检查最新版本的操作系统

linux - 如何编译/安装 node.js(无法配置 cxx 编译器!)(Ubuntu)。

node.js - MongoClient.connect - 错误: Could not locate any valid servers in initial seed list