当位置为空时如何在MongoDB中存储GeoJSON

4
当GeoJSON位置未提供或为空时,我应该如何存储它?我尝试将位置设置为null,但是会出现以下错误:
MongoError:无法提取地理键:{_id: ObjectId('...'),location:{ coordinates:[] } ...}
以下是我使用的代码。
if (!data.longitude || !data.latitude) {
    data.location = null;
}
else {
    data.location = {
        type: "Point",
        coordinates: [data.longitude, data.latitude]
    };
}
1个回答

6

简单来说,根本不需要设置它。问题可能会因为你的mongoose schema而变得更加复杂。从MongoDB的角度来看,如果属性不存在,它并不关心,并会在索引中忽略它。

实际上是“mongoose”在你不想创建结构时创造了这些东西,所以只需“告诉它”如果你没有提供任何数据,则不要包含该结构:

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

只要将coordinates数组设置为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的情况,而没有尝试默认值为undefined的情况。 - Sanka Darshana

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接