【问题标题】:Mongoose query returning nested document with empty arrayMongoose 查询返回带有空数组的嵌套文档
【发布时间】:2015-12-19 21:13:07
【问题描述】:

我有一个用于 geoJSON 多边形对象的猫鼬模式,结构如下:

var polygonZoneSchema = new mongoose.Schema({
    location: {
        'type': {
            type: String,
            enum: "Polygon",
            default: "Polygon"
        },
        coordinates: {
            type: [[[Number]]]
        }
    },
    zoneType: ObjectId,
    riskiness: {
        type: Number,
        default: 0
    }
});

在我的控制器中,我有一个列出所有多边形的函数:

polyZone.find({}).exec(function (err, collections) {
        console.log(collections[0].location.coordinates);
        if (err) {
            res.status(400);
            return res.send({reason: err.toString()});
        }
        res.send(collections);
    });

当通过 mongo 命令行检查我的数据库时,该集合包含:

{
    "_id": ObjectId("55fb6e7ab228f7343367116d"),
    "location": {
        "type": "Polygon",
        "coordinates": [
            [
                [0, 0],
                [0, 1],
                [1, 1],
                [1, 0],
                [0, 0]
            ]
        ]
    }
} {
    "_id": ObjectId("55fb6e7ab228f7343367116e"),
    "location": {
        "type": "Polygon",
        "coordinates": [
            [
                [1, 1],
                [1, 2],
                [2, 2],
                [2, 1],
                [1, 1]
            ]
        ]
    }
}

但是,当使用我的控制器函数时,返回的对象有一个空坐标数组:

[
  {
    "_id": "55fb6e7ab228f7343367116d",
    "riskiness": 0,
    "location": {
      "coordinates": [],
      "type": "Polygon"
    }
  },
  {
    "_id": "55fb6e7ab228f7343367116e",
    "riskiness": 0,
    "location": {
      "coordinates": [],
      "type": "Polygon"
    }
  }
]

这和猫鼬有关吗?我该如何解决?

【问题讨论】:

    标签: node.js mongodb mongoose


    【解决方案1】:

    事实证明,mongoose 中存在嵌套数组的错误。它已在 4..3 中修复,您可以在此处阅读更多信息 https://github.com/Automattic/mongoose/issues/1361

    直到那时我发现通过使用 Model.collection 我可以使用核心 mongo 驱动程序,它对嵌套数组没有任何问题

    【讨论】:

      【解决方案2】:

      是不是因为每个坐标中有 2 个数字而架构只指定了一个? IOW,应该

      coordinates: {
              type: [[[Number]]]
          }
      

      阅读

      coordinates: {
                  type: [[[Number, Number]]]
              }
      

      【讨论】:

      • 模式指定了一个数字数组,因此第三个内部数组 [Number] 看起来像 [1, 2]
      • 是的,这就是我提出问题的原因,我猜这不应该是答案的形式。 [1,2] 不是数字。您的示例数据在那里显示了 2 个逗号分隔的数字,但您的方案仅指定了一个数字。
      • 模式指定了一个大小为 n 的数字数组。 [], [1], [1, ... , n] 都是有效的例子
      猜你喜欢
      • 2015-04-18
      • 2018-06-12
      • 1970-01-01
      • 1970-01-01
      • 2014-08-05
      • 2012-06-23
      • 2019-11-30
      • 2012-10-17
      • 2017-08-08
      相关资源
      最近更新 更多