【问题标题】:How to store GeoJSON when location is empty in MongoDBMongoDB中位置为空时如何存储GeoJSON
【发布时间】:2018-10-23 14:39:07
【问题描述】:

如果 GeoJSON 位置未提供或为空,我如何存储它?我尝试将位置设置为空,但它给出了以下错误

MongoError: 无法提取地理键:{ _id: ObjectId('...'), location: { coordinates: [] } ...

以下是我使用的代码。

if (!data.longitude || !data.latitude) {
    data.location = null;
}
else {
    data.location = {
        type: "Point",
        coordinates: [data.longitude, data.latitude]
    };
}

【问题讨论】:

    标签: mongodb mongoose


    【解决方案1】:

    简单地说,根本不要设置它。您的猫鼬模式可能会使问题更加复杂。从 MongoDB 的角度来看,它并不关心该属性是否根本不存在,并将随后在索引中忽略它。

    它是“猫鼬”,它会在您不想要的时候实际创建东西,所以如果您不提供任何数据,只需“告诉它”不要包含结构:

      location: {
        type: { type: String },
        coordinates: { type: [], default: undefined }
      }
    

    只要将coordinates数组设置为default到undefined值,那么mongoose在持久化到数据库时就不会尝试将“空数组”添加到文档中,这会导致索引的问题。

    作为一个完整的演示:

    const { Schema } = mongoose = require('mongoose');
    
    const uri = 'mongodb://localhost/test';
    
    mongoose.Promise = global.Promise;
    mongoose.set('debug', true);
    
    const geoSchema = new Schema({
      name: String,
      location: {
        type: { type: String },
        coordinates: { type: [], default: undefined }
      }
    });
    
    const GeoTest = mongoose.model('GeoTest', geoSchema);
    
    
    const log = data => console.log(JSON.stringify(data, undefined, 2));
    
    (async function() {
    
      try {
    
        const conn = await mongoose.connect(uri);
    
        await Promise.all(Object.entries(conn.models).map(([k,m]) => m.remove()));
    
        await GeoTest.insertMany([
          {
            "name": "Sydney",
            "location": {
              "type": "Point",
              "coordinates": [
                151.21170043945312,
                -33.86414397991936
              ]
            }
          },
          { "name": "Nowhere" }
        ]);
    
        let results = await GeoTest.find();
        log(results);
    
      } catch(e) {
        console.error(e)
      } finally {
        process.exit()
      }
    
    })()
    

    其中显示存储的文档为:

    [
      {
        "location": {
          "type": "Point",
          "coordinates": [
            151.21170043945312,
            -33.86414397991936
          ]
        },
        "_id": "5af8e6c17c91d648feb26cc4",
        "name": "Sydney",
        "__v": 0
      },
      {
        "_id": "5af8e6c17c91d648feb26cc5",
        "name": "Nowhere",
        "__v": 0
      }
    ]
    

    因此,如果您实际上不提供任何location 数据,那么那里就什么都没有。这让 MongoDB 很高兴,因为在要为 "2d" 或 "2dsphere" 编制索引的属性中没有无效数据。

    【讨论】:

    • 谢谢。我只尝试使用默认值:null 而不是默认值:未定义。
    猜你喜欢
    • 2014-12-26
    • 2015-11-24
    • 2012-06-23
    • 2013-04-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-20
    相关资源
    最近更新 更多